// *********************************************************************** // Assembly : OpenAuth.Domain // Author : yubaolee // Created : 04-29-2016 // // Last Modified By : yubaolee // Last Modified On : 12-15-2020 // Contact : Microsoft // File: IUnitWork.cs // *********************************************************************** using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using OpenAuth.Repository.Core; namespace OpenAuth.Repository.Interface { /// /// 工作单元接口 /// 使用详见:http://doc.openauth.net.cn/core/unitwork.html /// 适合在一下情况使用: /// 1 在同一事务中进行多表操作 /// 2 需要多表联合查询 /// 因为架构采用的是EF访问数据库,暂时可以不用考虑采用传统Unit Work的注册机制 /// public interface IUnitWork where TDbContext:DbContext { /// /// EF默认情况下,每调用一次SaveChanges()都会执行一个单独的事务 /// 本接口实现在一个事务中可以多次执行SaveChanges()方法 /// void ExecuteWithTransaction(Action action); /// /// ExecuteWithTransaction方法的异步方式 /// Task ExecuteWithTransactionAsync(Func action); /// /// 返回DbContext,用于多线程等极端情况 /// /// DbContext GetDbContext(); /// /// 返回一个单独的实体,如果记录多于1个则取第一个 /// T FirstOrDefault(Expression> exp = null) where T:class; /// /// 判断指定条件的记录是否存在 /// bool Any(Expression> exp) where T:class; IQueryable Find(Expression> exp = null) where T:class; IQueryable Find(int pageindex = 1, int pagesize = 10, string orderby = "", Expression> exp = null) where T:class; int Count(Expression> exp = null) where T:class; /// /// 新增对象,如果Id为空,则会自动创建默认Id /// void Add(T entity) where T:BaseEntity; /// /// 批量新增对象,如果对象Id为空,则会自动创建默认Id /// void BatchAdd(T[] entities) where T:BaseEntity; /// /// 更新一个实体的所有属性 /// void Update(T entity) where T:class; void Delete(T entity) where T:class; /// /// 实现按需要只更新部分更新 /// 如:Update<User>(u =>u.Id==1,u =>new User{Name="ok"}) /// 该方法内部自动调用了SaveChanges(),需要ExecuteWithTransaction配合才能实现事务控制 /// /// 更新条件 /// 更新后的实体 void Update(Expression> where, Expression> entity) where T:class; /// /// 批量删除 /// 该方法内部自动调用了SaveChanges(),需要ExecuteWithTransaction配合才能实现事务控制 /// void Delete(Expression> exp) where T:class; void Save(); /// /// 该方法不支持EF自带的事务,需要ExecuteWithTransaction配合才能实现事务控制,详见:http://doc.openauth.net.cn/core/unitwork.html /// /// /// int ExecuteSql(string sql); /// /// 使用SQL脚本查询 /// /// T为数据库实体 /// IQueryable FromSql(string sql, params object[] parameters) where T:class; /// /// 使用SQL脚本查询 /// /// T为非数据库实体,需要在DbContext中增加对应的DbQuery /// IQueryable Query(string sql, params object[] parameters) where T : class; /// /// 执行存储过程 /// /// 存储过程名称 /// 存储过程参数 List ExecProcedure(string procName,params DbParameter[] sqlParams) where T : class; #region 异步接口 Task ExecuteSqlRawAsync(string sql); Task SaveAsync(); Task CountAsync(Expression> exp = null) where T : class; Task AnyAsync(Expression> exp) where T : class; Task FirstOrDefaultAsync(Expression> exp) where T : class; #endregion } }