NET7下EFCORE的通用增删查改类
NET7下EFCORE的通用增删查改类
代码摘录自《深入浅出ASP.NET CORE》
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | /// <summary> /// 所有仓储的约定,此接口仅作为约定,用于标识他们 /// </summary> /// <typeparam name="TEntity">传入仓储的实体模型</typeparam> /// <typeparam name="TPrimaryKey">传入仓储的主键类型</typeparam> public interface IRepository<TEntity,TPrimaryKey> where TEntity : class { #region 查询 IQueryable<TEntity> GetAll(); List<TEntity> GetAllList(); Task<List<TEntity>> GetAllListAsync(); List<TEntity> GetAllList(Expression<Func<TEntity, bool >> predicate); Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool >> predicate); TEntity FirstOrDefault(Expression<Func<TEntity, bool >> predicate); Task<TEntity> FirstOrDefaultAsycn(Expression<Func<TEntity, bool >> predicate); #endregion #region 新增 TEntity Insert(TEntity entity); Task<TEntity> InsertAsync(TEntity entity); #endregion #region 更新 TEntity Update(TEntity entity); Task<TEntity> UpdateAsync(TEntity entity); #endregion #region 删除 void Delete(TEntity entity); Task DeleteAsync(TEntity entity); void Delete(Expression<Func<TEntity, bool >> predicate); Task DeleteAsync(Expression<Func<TEntity, bool >> predicate); #endregion #region 总和计算 int Count(); Task< int > CountAsync(); int Count(Expression<Func<TEntity, bool >> predicate); Task< int > CountAsync(Expression<Func<TEntity, bool >> predicate); #endregion } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | /// <summary> /// 默认仓储的通用功能实现,用于所有的领域模型 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TPrimaryKey"></typeparam> public class RepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class { protected readonly AppDbContext _appDbContext; public RepositoryBase(AppDbContext appDbContext) { _appDbContext = appDbContext; } public virtual DbSet<TEntity> Table=>_appDbContext.Set<TEntity>(); public int Count() { return GetAll().Count(); } public int Count(Expression<Func<TEntity, bool >> predicate) { return GetAll().Where(predicate).Count(); } public async Task< int > CountAsync() { return await GetAll().CountAsync(); } public async Task< int > CountAsync(Expression<Func<TEntity, bool >> predicate) { return await GetAll().Where(predicate).CountAsync(); } public void Delete(TEntity entity) { AttachIfNot(entity); Table.Remove(entity); Save(); } public async Task DeleteAsync(TEntity entity) { AttachIfNot(entity); Table.Remove(entity); await SaveAsync(); } public void Delete(Expression<Func<TEntity, bool >> predicate) { foreach ( var entity in GetAll().Where(predicate).ToList()) { Delete(entity); } } public async Task DeleteAsync(Expression<Func<TEntity, bool >> predicate) { foreach ( var entity in GetAll().Where(predicate).ToList()) { await DeleteAsync(entity); } } public TEntity FirstOrDefault(Expression<Func<TEntity, bool >> predicate) { return GetAll().FirstOrDefault(predicate); } public async Task<TEntity> FirstOrDefaultAsycn(Expression<Func<TEntity, bool >> predicate) { return await GetAll().FirstOrDefaultAsync(predicate); } public IQueryable<TEntity> GetAll() { return Table.AsQueryable(); } public List<TEntity> GetAllList() { return GetAll().ToList(); } public List<TEntity> GetAllList(Expression<Func<TEntity, bool >> predicate) { return GetAll().Where(predicate).ToList(); } public async Task<List<TEntity>> GetAllListAsync() { return await GetAll().ToListAsync(); } public async Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool >> predicate) { return await GetAll().Where(predicate).ToListAsync(); } public TEntity Insert(TEntity entity) { var newEntity = Table.Add(entity).Entity; Save(); return newEntity; } protected void Save() { _appDbContext.SaveChanges(); } protected async Task SaveAsync() { await _appDbContext.SaveChangesAsync(); } /// <summary> /// 检查实体是否处于跟踪状态,如果是,则返回,如果不是,则添加跟踪状态 /// </summary> /// <param name="entity"></param> protected virtual void AttachIfNot(TEntity entity) { var entry = _appDbContext.ChangeTracker.Entries().FirstOrDefault(e => e.Entity == entity); if (entry != null ) { return ; } Table.Attach(entity); } public async Task<TEntity> InsertAsync(TEntity entity) { var entityEntry = await Table.AddAsync(entity); await SaveAsync(); return entityEntry.Entity; } public TEntity Update(TEntity entity) { AttachIfNot(entity); _appDbContext.Entry(entity).State = EntityState.Modified; Save(); return entity; } public async Task<TEntity> UpdateAsync(TEntity entity) { AttachIfNot(entity); _appDbContext.Entry(entity).State = EntityState.Modified; await SaveAsync(); return entity; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //假设有一学生接口需要有额外的登录接口,可新建一个IStudent接口,继承后只用加Login接口就行 public interface IStudentRepository :IRepository<Student, int > { bool Login( string username, string password); } //实现类除了要实现上面的接口,还要继承基类RepositoryBase public class StudentRepository : RepositoryBase<Student, int >, IStudentRepository { public StudentRepository(AppDbContext appDbContext) : base (appDbContext) { } public bool Login( string username, string password) { bool b = false ; //GetAll是基类中的方法,返回 iquerable b = GetAll().Where(a=>a.username=username && a.password=password).Count()>0 return b; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //使用记得注入 services.AddTransient( typeof (IRepository<,>), typeof (RepositoryBase<,>)); services.AddTransient<IStudentRepository, StudentRepository>(); //控制器里的代码 private readonly IRepository<Student, int > _studentRepository; private readonly IStudentRepository _studentRepository2; public WelcomeController( IRepository<Student, int > studentRepository, IStudentRepository studentRepository2 ) { _studentRepository = studentRepository; _studentRepository2 = studentRepository2; } public async Task<IActionResult> Index() { //_studentRepository2换成_studentRepository也成,只是没有Login方法 Models.Student student = await _studentRepository2.GetAll().FirstOrDefaultAsync(); int count = await _studentRepository2.CountAsync(); bool b = _studentRepository2.Login( "niunan" , "123456" ); string str = $ "取出一个学生:{student.Name},学生总数:{count}, 执行login方法结果:{false}" ; return Content($ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><div>原文:{src}</div><div>加密后:{jiami}</div><div>解密后:{jiemi}</div><div>{str}</div>" , "text/html" ); } |
撸码:复制、粘贴,拿起键盘就是“干”!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)