C# .NET6 EF 数据访问基础类
接口类
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using System.Linq.Expressions; namespace Demo { /// <summary> /// 模型处理服务接口 /// </summary> public interface IBaseDataRepository<T> where T : class { /// <summary> /// 取得数据库模型上下文 /// </summary> /// <returns></returns> DbContext DbContext { get; } /// <summary> /// 设置对象实体 /// </summary> public DbSet<T> DbSet { get; } /// <summary> /// 通过ID取得数据 /// </summary> /// <param name="id"></param> /// <returns></returns> T? Find(object id); /// <summary> /// 通过ID取得数据 /// </summary> /// <param name="id"></param> /// <returns></returns> Task<T?> FindAsync(object id); /// <summary> /// 取得数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> T? Find(Expression<Func<T, bool>> whereLambda); /// <summary> /// 通过ID取得数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<T?> FindAsync(Expression<Func<T, bool>> whereLambda); /// <summary> /// 取得数据列表 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> List<T> GetList(Expression<Func<T, bool>>? whereLambda = null); /// <summary> /// 取得数据列表 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<List<T>> GetListAsync(Expression<Func<T, bool>>? whereLambda = null); /// <summary> /// 取得数据记录数 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> int GetCount(Expression<Func<T, bool>>? whereLambda = null); /// <summary> /// 取得数据记录数 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<int> GetCountAsync(Expression<Func<T, bool>>? whereLambda = null); /// <summary> /// 判断数据是否存在 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> bool GetAny(Expression<Func<T, bool>> whereLambda); /// <summary> /// 判断数据是否存在 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> Task<bool> GetAnyAsync(Expression<Func<T, bool>> whereLambda); /// <summary> /// 添加数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> void Insert(T entity, bool saveFlag = false); /// <summary> /// 添加数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> Task InsertAsync(T entity, bool saveFlag = false); /// <summary> /// 修改数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> void Update(T entity, bool saveFlag = false); /// <summary> /// 修改数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> Task UpdateAsync(T entity, bool saveFlag = false); /// <summary> /// 删除数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> void Delete(T entity, bool saveFlag = false); /// <summary> /// 删除数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> Task DeleteAsync(T entity, bool saveFlag = false); /// <summary> /// 保存修改 /// </summary> void SaveChanges(); /// <summary> /// 保存修改 /// </summary> Task SaveChangesAsync(); /// <summary> /// 取得分页数据 /// </summary> /// <param name="whereLambda"></param> /// <param name="orderColumn"></param> /// <param name="orderType"></param> /// <param name="pageSize"></param> /// <param name="pageNum"></param> /// <returns></returns> PageList<T> GetPageData(Expression<Func<T, bool>>? whereLambda = null, string? orderColumn = null, OrderType? orderType = OrderType.ASC, int pageSize = 20, int pageNum = 1); /// <summary> /// 取得分页数据 /// </summary> /// <param name="whereLambda"></param> /// <param name="orderColumn"></param> /// <param name="orderType"></param> /// <param name="pageSize"></param> /// <param name="pageNum"></param> /// <returns></returns> Task<PageList<T>> GetPageDataAsync(Expression<Func<T, bool>>? whereLambda = null, string? orderColumn = null, OrderType? orderType = OrderType.ASC, int pageSize = 20, int pageNum = 1); /// <summary> /// 开始事务 /// </summary> /// <returns></returns> IDbContextTransaction BeginTransaction(); /// <summary> /// 开始事务 /// </summary> /// <returns></returns> Task<IDbContextTransaction> BeginTransactionAsync(); /// <summary> /// 提交事务 /// </summary> /// <returns></returns> void CommitTransaction(); /// <summary> /// 提交事务 /// </summary> /// <returns></returns> Task CommitTransactionAsync(); /// <summary> /// 事务回滚 /// </summary> void RollbackTransaction(); /// <summary> /// 回滚事务 /// </summary> /// <returns></returns> Task RollbackTransactionAsync(); } }
实现类
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using System.Linq.Expressions; namespace Demo { /// <summary> /// 模型处理服务实现 /// </summary> public class BaseDataRepository<T> : IBaseDataRepository<T> where T : class { /// <summary> /// 数据库上下文 /// </summary> protected readonly DbContext _context; /// <summary> /// 构造函数 /// </summary> /// <param name="context"></param> public BaseDataRepository(DbContext context) { _context = context; } /// <summary> /// 数据库上下文 /// </summary> /// <returns></returns> public DbContext DbContext { get { return _context; } } /// <summary> /// 设置对象实体 /// </summary> public DbSet<T> DbSet { get { return _context.Set<T>(); } } /// <summary> /// 通过ID取得数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public T? Find(object id) { return _context.Set<T>().Find(id); } /// <summary> /// 通过ID取得数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<T?> FindAsync(object id) { return await _context.Set<T>().FindAsync(id); } /// <summary> /// 取得数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public T? Find(Expression<Func<T, bool>> whereLambda) { return _context.Set<T>().Where(whereLambda).FirstOrDefault(); } /// <summary> /// 通过ID取得数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<T?> FindAsync(Expression<Func<T, bool>> whereLambda) { return await _context.Set<T>().Where(whereLambda).FirstOrDefaultAsync(); } /// <summary> /// 取得数据列表 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public List<T> GetList(Expression<Func<T, bool>>? whereLambda = null) { if (whereLambda != null) { return _context.Set<T>().Where(whereLambda).ToList(); } else { return _context.Set<T>().ToList(); } } /// <summary> /// 取得数据列表 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<List<T>> GetListAsync(Expression<Func<T, bool>>? whereLambda = null) { if (whereLambda != null) { return await _context.Set<T>().Where(whereLambda).ToListAsync(); } else { return await _context.Set<T>().ToListAsync(); } } /// <summary> /// 取得数据记录数 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public int GetCount(Expression<Func<T, bool>>? whereLambda = null) { if (whereLambda != null) { return _context.Set<T>().Where(whereLambda).Count(); } else { return _context.Set<T>().Count(); } } /// <summary> /// 取得数据记录数 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<int> GetCountAsync(Expression<Func<T, bool>>? whereLambda = null) { if (whereLambda != null) { return await _context.Set<T>().Where(whereLambda).CountAsync(); } else { return await _context.Set<T>().CountAsync(); } } /// <summary> /// 判断数据是否存在 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public bool GetAny(Expression<Func<T, bool>> whereLambda) { return _context.Set<T>().Any(whereLambda); } /// <summary> /// 判断数据是否存在 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<bool> GetAnyAsync(Expression<Func<T, bool>> whereLambda) { return await _context.Set<T>().AnyAsync(whereLambda); } /// <summary> /// 添加数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> public void Insert(T entity, bool saveFlag = false) { _context.Add(entity); if (saveFlag) _context.SaveChanges(); } /// <summary> /// 添加数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> /// <returns></returns> public async Task InsertAsync(T entity, bool saveFlag = false) { _context.Add(entity); if (saveFlag) await _context.SaveChangesAsync(); } /// <summary> /// 修改数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> public void Update(T entity, bool saveFlag = false) { _context.Entry(entity).State = EntityState.Modified; if (saveFlag) _context.SaveChanges(); } /// <summary> /// 修改数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> /// <returns></returns> public async Task UpdateAsync(T entity, bool saveFlag = false) { _context.Entry(entity).State = EntityState.Modified; if (saveFlag) await _context.SaveChangesAsync(); } /// <summary> /// 删除数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> public void Delete(T entity, bool saveFlag = false) { _context.Entry(entity).State = EntityState.Deleted; if (saveFlag) _context.SaveChanges(); } /// <summary> /// 删除数据 /// </summary> /// <param name="entity"></param> /// <param name="saveFlag"></param> /// <returns></returns> public async Task DeleteAsync(T entity, bool saveFlag = false) { _context.Entry(entity).State = EntityState.Deleted; if (saveFlag) await _context.SaveChangesAsync(); } /// <summary> /// 保存修改 /// </summary> public void SaveChanges() { _context.SaveChangesAsync(); } /// <summary> /// 保存修改 /// </summary> public async Task SaveChangesAsync() { await _context.SaveChangesAsync(); } /// <summary> /// 取得分页数据 /// </summary> /// <param name="whereLambda"></param> /// <param name="orderColumn"></param> /// <param name="orderType"></param> /// <param name="pageSize"></param> /// <param name="pageNum"></param> /// <returns></returns> public PageList<T> GetPageData(Expression<Func<T, bool>>? whereLambda = null, string? orderColumn = null, OrderType? orderType = OrderType.ASC, int pageSize = 20, int pageNum = 1) { // IQueryable var quary = _context.Set<T>().AsQueryable(); // where if (whereLambda != null) { quary = quary.Where(whereLambda); } // count var totalCount = quary.Count(); // order by if (orderColumn != null) { if (orderType == OrderType.ASC) quary = quary.OrderBy(GetEntityLambda(orderColumn)).AsQueryable(); else quary = quary.OrderByDescending(GetEntityLambda(orderColumn)).AsQueryable(); } // limit quary = quary.Skip(pageSize * (pageNum - 1)).Take(pageSize).AsQueryable(); // select var list = quary.ToList(); // PageList return new PageList<T>(pageSize, pageNum, totalCount, list); } /// <summary> /// 取得分页数据 /// </summary> /// <param name="whereLambda"></param> /// <param name="orderColumn"></param> /// <param name="orderType"></param> /// <param name="pageSize"></param> /// <param name="pageNum"></param> /// <returns></returns> public async Task<PageList<T>> GetPageDataAsync(Expression<Func<T, bool>>? whereLambda = null, string? orderColumn = null, OrderType? orderType = OrderType.ASC, int pageSize = 20, int pageNum = 1) { // IQueryable var quary = _context.Set<T>().AsQueryable(); // where if (whereLambda != null) { quary = quary.Where(whereLambda); } // count var totalCount = await quary.CountAsync(); // order by if (orderColumn != null) { if (orderType == OrderType.ASC) quary = quary.OrderBy(GetEntityLambda(orderColumn)).AsQueryable(); else quary = quary.OrderByDescending(GetEntityLambda(orderColumn)).AsQueryable(); } // limit quary = quary.Skip(pageSize * (pageNum - 1)).Take(pageSize).AsQueryable(); // select var list = await quary.ToListAsync(); // PageList return new PageList<T>(pageSize, pageNum, totalCount, list); } /// <summary> /// 开始事务 /// </summary> /// <returns></returns> public IDbContextTransaction BeginTransaction() { return _context.Database.BeginTransaction(); } /// <summary> /// 开始事务 /// </summary> /// <returns></returns> public async Task<IDbContextTransaction> BeginTransactionAsync() { return await _context.Database.BeginTransactionAsync(); } /// <summary> /// 提交事务 /// </summary> /// <returns></returns> public void CommitTransaction() { _context.Database.CommitTransaction(); } /// <summary> /// 提交事务 /// </summary> /// <returns></returns> public async Task CommitTransactionAsync() { await _context.Database.CommitTransactionAsync(); } /// <summary> /// 回滚事务 /// </summary> /// <returns></returns> public void RollbackTransaction() { _context.Database.RollbackTransaction(); } /// <summary> /// 回滚事务 /// </summary> /// <returns></returns> public async Task RollbackTransactionAsync() { await _context.Database.RollbackTransactionAsync(); } /// <summary> /// 根据字段名称取得对象的Lambda表达式 /// </summary> /// <param name="column"></param> /// <returns></returns> private Expression<Func<T, object>> GetEntityLambda(string column) { // 创建一个表示输入参数的ParameterExpression var parameter = Expression.Parameter(typeof(T), "x"); // 创建一个表示字段访问的MemberExpression var property = Expression.Property(parameter, column); // 创建Lambda表达式,参数为输入参数,主体为属性访问表达式 var lambdaExpression = Expression.Lambda<Func<T, object>>(property, parameter); //// 创建一个Lambda表达式的委托 //var func = lambdaExpression.Compile(); return lambdaExpression; } } }
分页
namespace Demo { /// <summary> /// 分页数据集合 /// </summary> /// <typeparam name="T">对象</typeparam> public class PageList<T> { /// <summary> /// 每页记录数 /// </summary> public int PageSize { get; set; } /// <summary> /// 页码 /// </summary> public int PageNum { get; set; } /// <summary> /// 总页数 /// </summary> public int PageCount { get { return TotalCount % PageSize == 0 ? TotalCount / PageSize : TotalCount / PageSize + 1; } } /// <summary> /// 总记录数 /// </summary> public int TotalCount { get; set; } /// <summary> /// 该页数据 /// </summary> public List<T>? DataList { get; set; } /// <summary> /// 构造函数 /// </summary> public PageList() { } /// <summary> /// 构造函数 /// </summary> /// <param name="pageSize"></param> /// <param name="pageNum"></param> /// <param name="totalCount"></param> /// <param name="dataList"></param> public PageList(int pageSize, int pageNum, int totalCount, List<T>? dataList) { PageSize = pageSize; PageNum = pageNum; TotalCount = totalCount; DataList = dataList; } } }
排序
namespace Demo { /// <summary> /// 数据库查询排序类型 /// </summary> public enum OrderType { /// <summary> /// 升序 /// </summary> ASC, /// <summary> /// 降序 /// </summary> DESC } }