在之前的泛型倉儲模式實作中,每個增刪改都呼叫了SaveChanges方法,導致每次更新都提交了事務,
在實際開發程序中,我們經常遇到同時操作多張表資料,那么按照之前的寫法,對資料庫提交了多次操作,開啟了多事務,不能保證資料的一致性,結合作業單元(UnitOfWork)是為了把多次操作放到同一事務中,要么都成功(Commit),要么都失敗(Rollback),保證了資料的一致性,
修改倉儲類
先把倉儲介面中增刪改介面無回傳(void)值型別,然后去倉儲實作類去掉SaveChanges方法,交給UOW統一處理
實作UOW
把SaveChanges抽離出來,定義IUnitOfWork介面
namespace NetCoreWebApi.Repository { /// <summary> /// 介面 /// </summary> public interface IUnitOfWork { /// <summary> /// 保存 /// </summary> /// <returns></returns> int SaveChanges(); } }
實作IUnitOfWork介面
using System; using Microsoft.EntityFrameworkCore; namespace NetCoreWebApi.Repository { /// <summary> /// 實作類 /// </summary> public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext { /// <summary> /// dbContext背景關系 /// </summary> private readonly TDbContext _dbContext; /// <summary> /// 建構式 /// </summary> /// <param name="dbContext"></param> public UnitOfWork(TDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// 保存 /// </summary> public int SaveChanges() { int code; try { code = _dbContext.SaveChanges(); } catch (DbUpdateException e) { throw new Exception(e.InnerException == null ? e.Message : e.InnerException.Message); } return code; } } }
UOW依賴注入
因為AddDbContext默認生命周期是Scoped,所以用AddScoped注冊UOW,確保每次請求共用同一個DbContex物件,
//注入DbContext services.AddDbContext<MyDbContext> (options => options.UseSqlServer(connectionStr,e => e.MigrationsAssembly("NetCoreWebApi.Model"))); //注入Uow依賴 services.AddScoped<IUnitOfWork, UnitOfWork<MyDbContext>>();
使用UOW
修改UserRepository業務層
using System.Collections.Generic; using System.Linq; using NetCoreWebApi.Model.Models; using NetCoreWebApi.Repository.Interface; using NetCoreWebApi.Repository.Repository; namespace NetCoreWebApi.Repository.Implement { /// <summary> /// 業務處理 /// </summary> public class UserRepository:IUserRepository { private readonly IUnitOfWork _unitOfWork; private readonly IRepository<TbUser> _userRepository; /// <summary> /// 建構式 /// </summary> /// <param name="userRepository"></param> /// <param name="unitOfWork"></param> public UserRepository(IRepository<TbUser> userRepository,IUnitOfWork unitOfWork) { _userRepository = userRepository; _unitOfWork = unitOfWork; } /// <summary> /// 添加用戶 /// </summary> /// <param name="entity"></param> /// <returns></returns> public int Add(TbUser entity) { _userRepository.Add(entity); return _unitOfWork.SaveChanges(); } /// <summary> /// 洗掉用戶 /// </summary> /// <param name="entity"></param> /// <returns></returns> public int Remove(TbUser entity) { _userRepository.Remove(entity); return _unitOfWork.SaveChanges(); } /// <summary> /// 查詢用戶 /// </summary> /// <returns></returns> public IList<TbUser> GetAll() { return _userRepository.GetAll().ToList(); } } }
遇到多倉儲持久化操作時,用建構式依賴注入相應的倉儲即可,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/89733.html
標籤:.NET Core
下一篇:從零開始搭建前后端分離的NetCore2.2(EF Core CodeFirst+Autofac)+Vue的專案框架之十二Swagger(引數)使用二
