Where to put savechanges in unit of work pattern with asp.net mvc?

asp.net-mvc-4 entity-framework entity-framework-6 razor-2

Question

I am using a generic repository pattern in asp.net mvc. I am familiar with repository pattern but not with Unit of work. I am reading several articles from google about this. But I am not sure if I use unit of work with asp.net mvc, where would I use Commit() method that will call the ef SaveChanges() method? Will I use it on repository layer or service layer or in Controller. Also, many others are saying that, Microsoft is already using Unit Of work built in with Entity Framework. So no need to use it separately or use it controller level or anywhere?

Thanks, Abdus Salam Azad.

1
0
11/24/2016 8:56:43 AM

Popular Answer

Yes,you have to do it inside the UnitOfWork.cs class.

UnitOfWork.cs

 public sealed class UnitOfWork : IUnitOfWork
   {

       private DbContext _dbContext;

       public UnitOfWork(DbContext context)
       {         
          _dbContext = context;
       }

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

       public void Dispose()
       {
           Dispose(true);
           GC.SuppressFinalize(this);
       }

      private void Dispose(bool disposing)
       {
           if (disposing)
           {
               if (_dbContext != null)
               {
                   _dbContext.Dispose();
                   _dbContext = null;
               }
           }
       }
   }

After that you can call UnitOfWork's Commit method inside the Service Layer.

EntityService.cs

public abstract class EntityService<T> : IEntityService<T> where T : BaseEntity
   {
       IUnitOfWork _unitOfWork;
       IGenericRepository<T> _repository;

       public EntityService(IUnitOfWork unitOfWork, IGenericRepository<T> repository)
       {
           _unitOfWork = unitOfWork;
           _repository = repository;
       }  

     public virtual void Create(T entity)
           {
               _repository.Add(entity);
               _unitOfWork.Commit(); //saving point        
           }

}

You can learn more about this pattern : Generic Repository and Unit of Work Pattern

1
10/15/2016 1:33:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow