0
votes

I have:

  1. Domain models (Model)
  2. Database entities (Entity)
  3. Repository: that accepts the model and converts it to the database entity (using automapper) and saves it to the database. In some cases returns back a Model object.

Example:

public class BaseRepository<T, U> : IRepository<T, U>
{
        public void Insert(T model)
        {            
            U entity= Mapper.Map<T, U>(model);
            dbContext.Set<U>().Add(entity);
            dbContext.SaveChanges();
        }
}

Now when creating repository objects from a business layer i would instantiate the repository as:

new BaseRepository<Model, Entity>()

PROBLEM Now this requires that the business layer have access to both the model and database entity projects. I want to avoid the reference of database entity to the business layer. My business layer should be able to instantiate repositories using only the domain model.

new BaseRepository<Model>() 

for which i need a repository as

public class BaseRepository<T> : IRepository<T>

But then i cant find a way to handle the mapping between model and entity(automapper).

Is what i am asking valid? OR is my requirement absurd?

Note: I think my business layer should not have a reference to database entities because i do not want anyone using database entities directly. They should be working only with the model classes.

1

1 Answers

-1
votes

So the answer is simple. Bit of a silly question to begin with. The declaration for IRep was wrong.

BaseRep<T,U>:IRep<T> instead of IRep<T, U>.
  1. The rep interface should be:

    public interface IRepository<T>
        where T : class
    {
        void Insert(T model);           
        IEnumerable<T> GetAll();
    }
    
  2. The base repository should be:

        public class BaseRepository<T, U> : IRepository<T>
                where T : class
                where U : class
        {
        protected readonly IPARS_ADOEntities dbContext;
    
        public BaseRepository()
            : this(new IPARS_ADOEntities())
        {
    
        }
    
        public BaseRepository(IPARS_ADOEntities dbContext)
        {
            this.dbContext = dbContext;
        }
    
        public void Insert(T model)
        {            
            U entity = Mapper.Map<T, U>(model);
            dbContext.Set<U>().Add(entity);
            dbContext.SaveChanges();
        }            
    
        public IEnumerable<T> GetAll()
        {
            IEnumerable<U> entities = dbContext.Set<U>();
            return Mapper.Map<IEnumerable<U>, IEnumerable<T>>(entities);
        }
    }
    
  3. In the business layer:

    public class BizLayer 
    {
        public List<EmployeeModel> GetEmployee(IRepository<EmployeeModel> rep)
        {
            return rep.GetAll();
        }    
     }
    
  4. From the presentation or application root you inject the dependency:

    bizlayer.GetEmployees(new IRepository<EmployeeModel, EmployeeEntity>())