#author("2022-05-17T13:36:35+08:00","default:Admin","Admin") [[.NET Core]] #author("2023-11-12T15:02:53+08:00","default:Admin","Admin") [[ASP.NET Core Web]] &color(red){※前提条件:本文基于 .NET Core 2.0 创作}; #contents * 概要 [#wb70db3a] Repository(仓储)是DDD(领域驱动设计)中的经典思想,可以归纳为介于实际业务层(领域层)和数据访问层之间的层,能让领域层能在感觉不到数据访问层的情况下,完成与数据库的交互。和以往的DAO层相比,Repository层的设计理念更偏向于面向对象,而淡化直接对数据表进行的CRUD操作 * 基类仓储接口 [#k852a3b0] 基类接口,声明一些所有仓储层接口都拥有的公共功能 #codeprettify{{ /// <summary> /// 基类仓储接口 /// </summary> /// <typeparam name="TEntity">Model类型</typeparam> public interface IBaseRepository<TEntity> where TEntity: class { Task<TEntity> QueryById(object objId); Task<TEntity> QueryById(object objId, bool blnUseCache = false); Task<List<TEntity>> QueryByIDs(object[] lstIds); Task<int> Add(TEntity model); Task<int> Add(List<TEntity> listEntity); Task<bool> DeleteById(object id); Task<bool> Delete(TEntity model); Task<bool> DeleteByIds(object[] ids); Task<bool> Update(TEntity model); Task<bool> Update(TEntity entity, string strWhere); Task<bool> Update(object operateAnonymousObjects); Task<bool> Update(TEntity entity, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string strWhere = ""); Task<List<TEntity>> Query(); Task<List<TEntity>> Query(string strWhere); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string strOrderByFileds); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true); Task<List<TEntity>> Query(string strWhere, string strOrderByFileds); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int intTop, string strOrderByFileds); Task<List<TEntity>> Query(string strWhere, int intTop, string strOrderByFileds); Task<List<TEntity>> QuerySql(string strSql, SugarParameter[] parameters = null); Task<DataTable> QueryTable(string strSql, SugarParameter[] parameters = null); Task<List<TEntity>> Query( Expression<Func<TEntity, bool>> whereExpression, int intPageIndex, int intPageSize, string strOrderByFileds); Task<List<TEntity>> Query(string strWhere, int intPageIndex, int intPageSize, string strOrderByFileds); Task<PageModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); Task<List<TResult>> QueryMuch<T, T2, T3, TResult>( Expression<Func<T, T2, T3, object[]>> joinExpression, Expression<Func<T, T2, T3, TResult>> selectExpression, Expression<Func<T, T2, T3, bool>> whereLambda = null) where T : class, new(); } }} * 构建接口 [#l6dd1417] 根据之前建立的Model类,继承这个基类接口来构建接口(以UserRole为例) #codeprettify{{ /// <summary> /// 继承基类接口创建的接口,若有额外方法可以在此处扩展 /// </summary> public interface IUserRoleRepository : IBaseRepository<UserRole> { } }} 考虑到事务控制的需要,在仓储接口层新增文件夹UnitOfWork,实现事务控制单元,代码为 #codeprettify{{ public interface IUnitOfWork { SqlSugarClient GetDbClient(); void BeginTran(); void CommitTran(); void RollbackTran(); } }} #hr(); コメント: #comment_kcaptcha