一、各层公用基类
IBaseServices.cs
public interface IBaseServices<TEntity> where TEntity : class { #region Add Task<TEntity> Add(TEntity entity); Task<int> Add(List<TEntity> listEntity); #endregion #region UPDATE Task<bool> Update(TEntity entity); Task<bool> Update(TEntity model, params string[] propertyNames); Task<bool> Update(TEntity model, Expression<Func<TEntity, bool>> whereLambda, params string[] modifiedPropertyNames); #endregion #region DELETE Task<bool> Delete(TEntity entity); Task<bool> DeleteBy(Expression<Func<TEntity, bool>> delWhere); #endregion #region Select Task<TEntity> QueryBy(Expression<Func<TEntity, bool>> whereLambda); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereLambda); Task<List<TEntity>> Query(); #region 排序查询 Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true); Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int top, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true); #endregion #region 分页查询 Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true); Task<PageModel<TEntity>> QueryPage<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true); #endregion #endregion #region ORTHER Task<List<TEntity>> Query(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text); Task<int> Execute(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text); #endregion ORTHER }
BaseServices.cs
public class BaseServices<TEntity> : IBaseServices<TEntity> where TEntity : class, new() { public IBaseDao<TEntity> BaseDal;//通过在子类的构造函数中注入,这里是基类,不用构造函数 #region Add /// <summary> /// 写入实体数据 /// </summary> /// <param name="entity">实体类</param> /// <returns></returns> public async Task<TEntity> Add(TEntity entity) { return await BaseDal.Add(entity); } /// <summary> /// 批量插入实体(速度快) /// </summary> /// <param name="listEntity">实体集合</param> /// <returns>影响行数</returns> public async Task<int> Add(List<TEntity> listEntity) { return await BaseDal.Add(listEntity); } #endregion #region UPDATE /// <summary> /// 更新实体数据 /// </summary> /// <param name="entity">博文实体类</param> /// <returns></returns> public async Task<bool> Update(TEntity entity) { return await BaseDal.Update(entity); } public async Task<bool> Update(TEntity model, params string[] propertyNames) { return await BaseDal.Update(model, propertyNames); } public async Task<bool> Update(TEntity model, Expression<Func<TEntity, bool>> whereLambda, params string[] modifiedPropertyNames) { return await BaseDal.Update(model, whereLambda, modifiedPropertyNames); } #endregion #region DELETE /// <summary> /// 根据实体删除一条数据 /// </summary> /// <param name="entity">博文实体类</param> /// <returns></returns> public async Task<bool> Delete(TEntity entity) { return await BaseDal.Delete(entity); } /// <summary> /// 删除指定ID的数据 /// </summary> /// <param name="id">主键ID</param> /// <returns></returns> public async Task<bool> DeleteBy(Expression<Func<TEntity, bool>> delWhere) { return await BaseDal.DeleteBy(delWhere); } #endregion #region Select public async Task<TEntity> QueryBy(Expression<Func<TEntity, bool>> whereLambda) { return await BaseDal.QueryBy(whereLambda); } public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereLambda) { return await BaseDal.Query(whereLambda); } public async Task<List<TEntity>> Query() { return await BaseDal.Query(); } #region 排序查询 public async Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true) { return await BaseDal.Query(whereLambda, orderLambda, isAsc); } public async Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int top, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true) { return await BaseDal.Query(whereLambda, top, orderLambda, isAsc); } #endregion #region 分页查询 public async Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true) { return await BaseDal.Query(whereLambda, pageIndex, pageSize, orderByLambda, isAsc); } public async Task<PageModel<TEntity>> QueryPage<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true) { return await BaseDal.QueryPage(whereLambda, pageIndex, pageSize, orderByLambda, isAsc); } #endregion #endregion #region ORTHER /// <summary> /// 执行存储过程或自定义sql语句--返回集合 /// </summary> /// <param name="sql"></param> /// <param name="parms"></param> /// <param name="cmdType"></param> /// <returns></returns> public async Task<List<TEntity>> Query(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text) { return await BaseDal.Query(sql, parms, cmdType); } /// <summary> /// 自定义语句和存储过程的增删改--返回影响的行数 /// </summary> /// <param name="sql"></param> /// <param name="parms"></param> /// <param name="cmdType"></param> /// <returns></returns> public async Task<int> Execute(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text) { return await BaseDal.Execute(sql, parms, cmdType); } #endregion ORTHER }
IBaseDao.cs
public interface IBaseDao<TEntity> where TEntity : class { #region Add Task<TEntity> Add(TEntity entity); Task<int> Add(List<TEntity> listEntity); #endregion #region UPDATE Task<bool> Update(TEntity entity); Task<bool> Update(TEntity model, params string[] propertyNames); Task<bool> Update(TEntity model, Expression<Func<TEntity, bool>> whereLambda, params string[] modifiedPropertyNames); #endregion #region DELETE Task<bool> Delete(TEntity entity); Task<bool> DeleteBy(Expression<Func<TEntity, bool>> delWhere); #endregion #region Select Task<TEntity> QueryBy(Expression<Func<TEntity, bool>> whereLambda); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereLambda); Task<List<TEntity>> Query(); #region 排序查询 Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true); Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int top, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true); #endregion #region 分页查询 Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true); Task<PageModel<TEntity>> QueryPage<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true); #endregion #endregion #region ORTHER Task<List<TEntity>> Query(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text); Task<int> Execute(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text); #endregion ORTHER }
BaseDao.cs
public class BaseDao<TEntity> : IBaseDao<TEntity> where TEntity : class, new() { private BaseCoreContext _db; private readonly DbSet<TEntity> _dbSet; internal BaseCoreContext Db { get { return _db; } private set { _db = value; } } public BaseDao(BaseCoreContext mydbcontext) { this._db = mydbcontext as BaseCoreContext; this._dbSet = _db.Set<TEntity>(); } #region Add /// <summary> /// 写入实体数据 /// </summary> /// <param name="entity">实体类</param> /// <returns></returns> public async Task<TEntity> Add(TEntity entity) { _db.Set<TEntity>().Add(entity); await _db.SaveChangesAsync(); return entity; } /// <summary> /// 批量插入实体(速度快) /// </summary> /// <param name="listEntity">实体集合</param> /// <returns>影响行数</returns> public async Task<int> Add(List<TEntity> listEntity) { await _db.Set<TEntity>().AddRangeAsync(listEntity); return await _db.SaveChangesAsync(); } #endregion #region UPDATE /// <summary> /// 更新实体数据 /// </summary> /// <param name="entity">博文实体类</param> /// <returns></returns> public async Task<bool> Update(TEntity entity) { _db.Set<TEntity>().Update(entity); return await _db.SaveChangesAsync() > 0; } public async Task<bool> Update(TEntity model, params string[] propertyNames) { //3.1.1 将对象添加到EF中 EntityEntry entry = _db.Entry<TEntity>(model); //3.1.2 先设置对象的包装状态为 Unchanged entry.State = EntityState.Unchanged; //3.1.3 循环被修改的属性名数组 foreach (string propertyName in propertyNames) { //将每个被修改的属性的状态设置为已修改状态;这样在后面生成的修改语句时,就只为标识为已修改的属性更新 entry.Property(propertyName).IsModified = true; } return await _db.SaveChangesAsync() > 0; } public async Task<bool> Update(TEntity model, Expression<Func<TEntity, bool>> whereLambda, params string[] modifiedPropertyNames) { //3.2.1 查询要修改的数据 List<TEntity> listModifing = _db.Set<TEntity>().Where(whereLambda).ToList(); //3.2.2 获取实体类类型对象 Type t = typeof(TEntity); //3.2.3 获取实体类所有的公共属性 List<PropertyInfo> propertyInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); //3.2.4 创建实体属性字典集合 Dictionary<string, PropertyInfo> dicPropertys = new Dictionary<string, PropertyInfo>(); //3.2.5 将实体属性中要修改的属性名 添加到字典集合中 键:属性名 值:属性对象 propertyInfos.ForEach(p => { if (modifiedPropertyNames.Contains(p.Name)) { dicPropertys.Add(p.Name, p); } }); //3.2.6 循环要修改的属性名 foreach (string propertyName in modifiedPropertyNames) { //判断要修改的属性名是否在实体类的属性集合中存在 if (dicPropertys.ContainsKey(propertyName)) { //如果存在,则取出要修改的属性对象 PropertyInfo proInfo = dicPropertys[propertyName]; //取出要修改的值 object newValue = proInfo.GetValue(model, null); //批量设置要修改对象的属性 foreach (TEntity item in listModifing) { //为要修改的对象的要修改的属性设置新的值 proInfo.SetValue(item, newValue, null); } } } //一次性生成sql语句 到数据库执行 return await _db.SaveChangesAsync() > 0; } #endregion #region DELETE /// <summary> /// 根据实体删除一条数据 /// </summary> /// <param name="entity">博文实体类</param> /// <returns></returns> public async Task<bool> Delete(TEntity entity) { //var i = await Task.Run(() => _db.Deleteable(entity).ExecuteCommand()); //return i > 0; //return await _db.Deleteable(entity).ExecuteCommandHasChangeAsync(); _db.Set<TEntity>().Attach(entity); _db.Set<TEntity>().Remove(entity); return await _db.SaveChangesAsync() > 0; } /// <summary> /// 删除指定ID的数据 /// </summary> /// <param name="id">主键ID</param> /// <returns></returns> public async Task<bool> DeleteBy(Expression<Func<TEntity, bool>> delWhere) { //2.1.1 查询要删除的数据 List<TEntity> listDeleting = _db.Set<TEntity>().Where(delWhere).ToList(); //2.1.2 将要删除的数据 用删除方法添加到 EF 容器中 listDeleting.ForEach(u => { _db.Set<TEntity>().Attach(u); //先附加到EF 容器 _db.Set<TEntity>().Remove(u); //标识为删除状态 }); //2.1.3 一次性生成sql语句 到数据库执行删除 return await _db.SaveChangesAsync() > 0; } #endregion #region Select public async Task<TEntity> QueryBy(Expression<Func<TEntity, bool>> whereLambda) { //return await Task.Run(() => _db.Queryable<TEntity>().InSingle(objId)); //return await _db.Queryable<TEntity>().In(objId).SingleAsync(); return await _db.Set<TEntity>().Where(whereLambda).AsNoTracking().FirstOrDefaultAsync(); } public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereLambda) { return await _db.Set<TEntity>().Where(whereLambda).AsNoTracking().ToListAsync(); } public async Task<List<TEntity>> Query() { return await _db.Set<TEntity>().AsNoTracking().ToListAsync(); } #region 排序查询 public async Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true) { if (isAsc) { return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda).AsNoTracking().ToListAsync(); } else { return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda).AsNoTracking().ToListAsync(); } } public async Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int top, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true) { if (isAsc) { return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda).Take(top).AsNoTracking().ToListAsync(); } else { return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda).Take(top).AsNoTracking().ToListAsync(); } } #endregion #region 分页查询 public async Task<List<TEntity>> Query<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true) { // 分页 一定注意: Skip 之前一定要 OrderBy if (isAsc) { return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync(); } else { return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync(); } } public async Task<PageModel<TEntity>> QueryPage<TKey>(Expression<Func<TEntity, bool>> whereLambda, int pageIndex, int pageSize, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true) { var rowCount = await _db.Set<TEntity>().Where(whereLambda).CountAsync(); int pageCount = (Math.Ceiling(rowCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt(); List<TEntity> list = null; if (isAsc) { list = await _db.Set<TEntity>().OrderBy(orderByLambda).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync(); } else { list = await _db.Set<TEntity>().OrderByDescending(orderByLambda).Where(whereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync(); } return new PageModel<TEntity>() { dataCount = rowCount, pageCount = pageCount, page = pageIndex, PageSize = pageSize, data = list }; } #endregion #endregion #region ORTHER /// <summary> /// 执行存储过程或自定义sql语句--返回集合 /// </summary> /// <param name="sql"></param> /// <param name="parms"></param> /// <param name="cmdType"></param> /// <returns></returns> public async Task<List<TEntity>> Query(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text) { //存储过程(exec getActionUrlId @name,@ID) if (cmdType == CommandType.StoredProcedure) { StringBuilder paraNames = new StringBuilder(); foreach (var sqlPara in parms) { paraNames.Append($" @{sqlPara},"); } sql = paraNames.Length > 0 ? $"exec {sql} {paraNames.ToString().Trim(‘,‘)}" : $"exec {sql} "; } return await _db.Set<TEntity>().FromSqlRaw(sql).ToListAsync(); } /// <summary> /// 回滚 /// </summary> public void RollBackChanges() { var items = _db.ChangeTracker.Entries().ToList(); items.ForEach(o => o.State = EntityState.Unchanged); } /// <summary> /// 自定义语句和存储过程的增删改--返回影响的行数 /// </summary> /// <param name="sql"></param> /// <param name="parms"></param> /// <param name="cmdType"></param> /// <returns></returns> public async Task<int> Execute(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text) { //存储过程(exec getActionUrlId @name,@ID) if (cmdType == CommandType.StoredProcedure) { StringBuilder paraNames = new StringBuilder(); foreach (var sqlPara in parms) { paraNames.Append($" @{sqlPara},"); } sql = paraNames.Length > 0 ? $"exec {sql} {paraNames.ToString().Trim(‘,‘)}" : $"exec {sql} "; } int ret = await _db.Database.ExecuteSqlRawAsync(sql, parms.ToArray()); return 0; } #endregion ORTHER }
二、以角色为例
新建IRoleServices、RoleServices
public interface IRoleServices : IBaseServices<SysRole> { }
public class RoleServices : BaseServices<SysRole>, IRoleServices { IBaseDao<SysRole> _dal; public RoleServices(IBaseDao<SysRole> dal) { this._dal = dal; base.BaseDal = dal; } }
三、调用
新建 RoleController,调用/api/Role/Get
[Route("api/[controller]/[action]")] [ApiController] public class RoleController : ControllerBase { readonly IRoleServices _roleServices; public RoleController(BaseCoreContext db) { _roleServices = new RoleServices(new BaseDao<SysRole>(db)); } [HttpGet] public async Task<MessageModel<PageModel<SysRole>>> Get(int page = 1, string key = "") { if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { key = ""; } int intPageSize = 50; var data = await _roleServices.QueryPage(a => a.IsDeleted != true && (a.RoleName != null && a.RoleName.Contains(key)), page, intPageSize, a => a.Id, false); return new MessageModel<PageModel<SysRole>>() { msg = "获取成功", success = data.dataCount >= 0, response = data }; } [HttpPost] public async Task<MessageModel<string>> Post([FromBody] SysRole role) { var data = new MessageModel<string>(); var m = (await _roleServices.Add(role)); data.success = m.Id > 0; if (data.success) { data.response = m.Id.ObjToString(); data.msg = "添加成功"; } return data; } [HttpPut] public async Task<MessageModel<string>> Put([FromBody] SysRole role) { var data = new MessageModel<string>(); if (role != null && role.Id > 0) { data.success = await _roleServices.Update(role); if (data.success) { data.msg = "更新成功"; data.response = role?.Id.ObjToString(); } } return data; } [HttpDelete] public async Task<MessageModel<string>> Delete(int id) { var data = new MessageModel<string>(); if (id > 0) { var userDetail = await _roleServices.QueryBy(a => a.Id == id); userDetail.IsDeleted = true; data.success = await _roleServices.Update(userDetail); if (data.success) { data.msg = "删除成功"; data.response = userDetail?.Id.ObjToString(); } } return data; } }
四、实例化
RoleController的构造函数的参数BaseCoreContext的实例是如何传进来的呢?前面Startup里的services.AddDbContextPool已经实现了注入
RoleServices的构造函数的参数IBaseDao<SysRole> dal,这一章是在RoleController的构造函数里手动实例化的,下一章学习依赖注入,就不再需要自己去实例化了,直接通过构造函数把实例注入进来即可。