用asp.net mvc将savechanges放在工作单元模式中的哪里?

问题描述 投票:0回答:2

我在asp.net mvc中使用通用存储库模式。我熟悉存储库模式,但不熟悉工作单元。我正在阅读谷歌关于此的几篇文章。但我不确定我是否使用asp.net mvc的工作单元,我将使用将调用ef SaveChanges()方法的Commit()方法?我会在存储库层或服务层或Controller中使用它吗?此外,许多其他人都说,微软已经在使用Entity Framework内置的工作单元。所以不需要单独使用它或使用控制器级别或任何地方?

谢谢Abdus Salam Azad。

entity-framework asp.net-mvc-4 entity-framework-6 razor-2
2个回答
1
投票

是的,你必须在UnitOfWork.cs课程内完成。

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;
               }
           }
       }
   }

之后,您可以在服务层内调用UnitOfWork的Commit方法。

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        
           }

}

您可以了解有关此模式的更多信息:Generic Repository and Unit of Work Pattern


0
投票

如果您对同一个事务有多个操作。然后在完成所有操作后,您需要最后放置您的savechanges()。如果成功,则所有操作都将成功,如果失败,则所有操作都将失败并恢复。

            _employeeService.UpdateVehicleDetail(model);
            _employeeService.UpdateLicenseDetail(model);
            await CurrentUnitOfWork.SaveChangesAsync();
© www.soinside.com 2019 - 2024. All rights reserved.