0

Hello I use entity framework with a unit of work pattern and I would like to know if in my application layer I should work directly with entities generated by entity framework or recreate POCO objects in my application layer and map my POCO?

Because I would like my application layer not to make any reference to my entities, I would like for example to create another project in my solution that could map my entities to my poco in my application but I don't know if this is a good practice and especially I don't know how to do it

Thank you in advance!

1 Answers1

0

In my UnitOfWork I have used a generic repository pattern that uses the models generated by the EF directly. The IRepository<T> interface looks a bit like this:

public interface IRepository<T> where T : class
{
    void Add(T entity);
    T GetById(long Id); 
     //etc - all the stuff you probably have
 }

I have implementation of the IRepository called Repository

public Repository<T> : IRepository<T>
{
     public readonly Infomaster _dbContext;

     public Repository(Infomaster dbContext)
      {
            _dbContext = dbContext;
       }

     public void Add(T entity)
     {
         _dbContext.Set<T>.Add(t);
     }
}

The use of the set and the type allows me to access the dataset (dbSet) of that particular type which allows me to create a generic pattern. You can use specific classes but it's a lot more work. This means in my UnitOfWork, I only need to do the following:

public class UnitOfWork : IUnitOfWork
{
     //Db context 
     Infomaster _dbContext;

     //User is a model from my EF
     public IRepository<User> UserRepository { get; private set; }

     public UnitOfWork()
     {
         _dbContext = new Infomaster();

          UserRepository = new Repository<User>(_dbContext);
     }

     public int Commit()
     {
          return _dbContext.Save(); 
     }
}

I find that is the best way and requires the use of the model classes, I am using a code first database but I have done with database first.

(from iPhone - can and will update from laptop)

Daniel Loudon
  • 725
  • 3
  • 16