EFCore封装仓储库
http://www.cnblogs.com/coldairarrow/p/9626691.html
利用EFCore 封装Repository(可扩展不同数据的sql操作)
本篇是对EFCore 进行下封装并实现基本的增删改查的同步异步方法及针对不同数据库的批量插入、sql语句直接操作数据库;
一、 先定义基础仓储接口IRepository
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 | public interface IRepository<TEntity,TKey> where TEntity : class { #region 查找数据 long Count(Expression<Func<TEntity, bool >> predicate = null ); Task< long > CountAsync(Expression<Func<TEntity, bool >> predicate = null ); TEntity Get(Expression<Func<TEntity, bool >> predicate, bool isNoTracking); Task<TEntity> GetAsync(Expression<Func<TEntity, bool >> predicate, bool isNoTracking); Task<TEntity> GetAsync(TKey id); IQueryable<TEntity> Load(Expression<Func<TEntity, bool >> predicate , bool isNoTracking); Task<IQueryable<TEntity>> LoadAsync(Expression<Func<TEntity, bool >> predicate , bool isNoTracking); List<TEntity> GetList(Expression<Func<TEntity, bool >> predicate, string ordering, bool isNoTracking ); Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool >> predicate, string ordering, bool isNoTracking ); #endregion #region 插入数据 bool Insert(TEntity entity, bool isSaveChange); Task< bool > InsertAsync(TEntity entity, bool isSaveChange); bool Insert(List<TEntity> entitys, bool isSaveChange = true ); Task< bool > InsertAsync(List<TEntity> entitys, bool isSaveChange); #endregion #region 删除(删除之前需要查询) bool Delete(TEntity entity, bool isSaveChange); bool Delete(List<TEntity> entitys, bool isSaveChange); Task< bool > DeleteAsync(TEntity entity, bool isSaveChange); Task< bool > DeleteAsync(List<TEntity> entitys, bool isSaveChange = true ); #endregion #region 修改数据 bool Update(TEntity entity, bool isSaveChange, List< string > updatePropertyList); Task< bool > UpdateAsync(TEntity entity, bool isSaveChange, List< string > updatePropertyList); bool Update(List<TEntity> entitys, bool isSaveChange); Task< bool > UpdateAsync(List<TEntity> entitys, bool isSaveChange ); #endregion #region 执行Sql语句 void BulkInsert<T>(List<T> entities); int ExecuteSql( string sql); Task< int > ExecuteSqlAsync( string sql); int ExecuteSql( string sql, List<DbParameter> spList); Task< int > ExecuteSqlAsync( string sql, List<DbParameter> spList); DataTable GetDataTableWithSql( string sql); DataTable GetDataTableWithSql( string sql, List<DbParameter> spList); #endregion |
二、实现IRepository接口
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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | public abstract class BaseRepository<TEntity,TKey> :IRepository<TEntity,TKey> where TEntity : class { private readonly DbSet<TEntity> _dbSet; public GeneralDbContext _dbContext { get ; } = null ; /// <summary> /// 连接字符串 /// </summary> protected string _connectionString { get ; set ; } /// <summary> /// 数据库类型 /// </summary> private DatabaseType _dbType { get ; set ; } public BaseRepository(GeneralDbContext context) { _dbContext = context; _dbSet = _dbContext.Set<TEntity>(); } public DatabaseFacade Database => _dbContext.Database; public IQueryable<TEntity> Entities => _dbSet.AsQueryable().AsNoTracking(); public int SaveChanges() { return _dbContext.SaveChanges(); } public async Task< int > SaveChangesAsync() { return await _dbContext.SaveChangesAsync(); } public bool Any(Expression<Func<TEntity, bool >> whereLambd) { return _dbSet.Where(whereLambd).Any(); } #region 插入数据 public bool Insert(TEntity entity, bool isSaveChange = true ) { _dbSet.Add(entity); if (isSaveChange) { return SaveChanges() > 0; } return false ; } public async Task< bool > InsertAsync(TEntity entity, bool isSaveChange = true ) { _dbSet.Add(entity); if (isSaveChange) { return await SaveChangesAsync() > 0; } return false ; } public bool Insert(List<TEntity> entitys, bool isSaveChange = true ) { _dbSet.AddRange(entitys); if (isSaveChange) { return SaveChanges() > 0; } return false ; } public async Task< bool > InsertAsync(List<TEntity> entitys, bool isSaveChange = true ) { _dbSet.AddRange(entitys); if (isSaveChange) { return await SaveChangesAsync() > 0; } return false ; } #endregion #region 删除 public bool Delete(TEntity entity, bool isSaveChange = true ) { _dbSet.Attach(entity); _dbSet.Remove(entity); return isSaveChange ? SaveChanges() > 0 : false ; } public bool Delete(List<TEntity> entitys, bool isSaveChange = true ) { entitys.ForEach(entity => { _dbSet.Attach(entity); _dbSet.Remove(entity); }); return isSaveChange ? SaveChanges() > 0 : false ; } public virtual async Task< bool > DeleteAsync(TEntity entity, bool isSaveChange = true ) { _dbSet.Attach(entity); _dbSet.Remove(entity); return isSaveChange ? await SaveChangesAsync() > 0 : false ; } public virtual async Task< bool > DeleteAsync(List<TEntity> entitys, bool isSaveChange = true ) { entitys.ForEach(entity => { _dbSet.Attach(entity); _dbSet.Remove(entity); }); return isSaveChange ? await SaveChangesAsync() > 0 : false ; } #endregion #region 更新数据 public bool Update(TEntity entity, bool isSaveChange = true , List< string > updatePropertyList = null ) { if (entity == null ) { return false ; } _dbSet.Attach(entity); var entry = _dbContext.Entry(entity); if (updatePropertyList == null ) { entry.State = EntityState.Modified; //全字段更新 } else { updatePropertyList.ForEach(c => { entry.Property(c).IsModified = true ; //部分字段更新的写法 }); } if (isSaveChange) { return SaveChanges() > 0; } return false ; } public bool Update(List<TEntity> entitys, bool isSaveChange = true ) { if (entitys == null || entitys.Count == 0) { return false ; } entitys.ForEach(c => { Update(c, false ); }); if (isSaveChange) { return SaveChanges() > 0; } return false ; } public async Task< bool > UpdateAsync(TEntity entity, bool isSaveChange = true , List< string > updatePropertyList = null ) { if (entity == null ) { return false ; } _dbSet.Attach(entity); var entry = _dbContext.Entry<TEntity>(entity); if (updatePropertyList == null ) { entry.State = EntityState.Modified; //全字段更新 } else { updatePropertyList.ForEach(c => { entry.Property(c).IsModified = true ; //部分字段更新的写法 }); } if (isSaveChange) { return await SaveChangesAsync() > 0; } return false ; } public async Task< bool > UpdateAsync(List<TEntity> entitys, bool isSaveChange = true ) { if (entitys == null || entitys.Count == 0) { return false ; } entitys.ForEach(c => { _dbSet.Attach(c); _dbContext.Entry<TEntity>(c).State = EntityState.Modified; }); if (isSaveChange) { return await SaveChangesAsync() > 0; } return false ; } #endregion #region 查找 public long Count(Expression<Func<TEntity, bool >> predicate = null ) { if (predicate == null ) { predicate = c => true ; } return _dbSet.LongCount(predicate); } public async Task< long > CountAsync(Expression<Func<TEntity, bool >> predicate = null ) { if (predicate == null ) { predicate = c => true ; } return await _dbSet.LongCountAsync(predicate); } public TEntity Get(TKey id) { if (id == null ) { return default (TEntity); } return _dbSet.Find(id); } public TEntity Get(Expression<Func<TEntity, bool >> predicate = null , bool isNoTracking = true ) { var data = isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate); return data.FirstOrDefault(); } public async Task<TEntity> GetAsync(TKey id) { if (id == null ) { return default (TEntity); } return await _dbSet.FindAsync(id); } public async Task<TEntity> GetAsync(Expression<Func<TEntity, bool >> predicate = null , bool isNoTracking = true ) { var data = isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate); return await data.FirstOrDefaultAsync(); } public async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool >> predicate = null , string ordering = "" , bool isNoTracking = true ) { var data = isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate); if (! string .IsNullOrEmpty(ordering)) { data = data.OrderByBatch(ordering); } return await data.ToListAsync(); } public List<TEntity> GetList(Expression<Func<TEntity, bool >> predicate = null , string ordering = "" , bool isNoTracking = true ) { var data = isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate); if (! string .IsNullOrEmpty(ordering)) { data = data.OrderByBatch(ordering); } return data.ToList(); } public async Task<IQueryable<TEntity>> LoadAsync(Expression<Func<TEntity, bool >> predicate = null , bool isNoTracking = true ) { if (predicate == null ) { predicate = c => true ; } return await Task.Run(() => isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate)); } public IQueryable<TEntity> Load(Expression<Func<TEntity, bool >> predicate = null , bool isNoTracking = true ) { if (predicate == null ) { predicate = c => true ; } return isNoTracking ? _dbSet.Where(predicate).AsNoTracking() : _dbSet.Where(predicate); } #endregion #region SQL语句 public virtual void BulkInsert<T>(List<T> entities) { } public int ExecuteSql( string sql) { return _dbContext.Database.ExecuteSqlCommand(sql) ; } public Task< int > ExecuteSqlAsync( string sql) { return _dbContext.Database.ExecuteSqlCommandAsync(sql); } public int ExecuteSql( string sql, List<DbParameter> spList) { return _dbContext.Database.ExecuteSqlCommand(sql, spList.ToArray()); } public Task< int > ExecuteSqlAsync( string sql, List<DbParameter> spList) { return _dbContext.Database.ExecuteSqlCommandAsync(sql, spList.ToArray()); } public virtual DataTable GetDataTableWithSql( string sql) { throw new NotImplementedException(); } public virtual DataTable GetDataTableWithSql( string sql, List<DbParameter> spList) { throw new NotImplementedException(); } #endregion } |
三、BaseRepository是个抽象类,有些比较复杂的sql语句通过EF来处理比较麻烦,还需要直接操作sql语句的方法,
因不同的数据库sql语句不一样,针对不同的数据,继承BaseRepository这个基类,重写sql语句方法,
下面简单实现SqlServerRepository仓储
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 | public class SqlServerRepository<TEntity,TKey>: BaseRepository<TEntity,TKey>,IRepository<TEntity,TKey> where TEntity : class { protected ConfigOption _dbOpion; public SqlServerRepository(GeneralDbContext generalDbContext,IOptionsSnapshot<ConfigOption> options) : base (generalDbContext) { _dbOpion = options.Get( "config" ); _connectionString = _dbOpion.ReadWriteHosts; } #region 插入数据 /// <summary> /// 使用Bulk批量插入数据(适合大数据量,速度非常快) /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="entities">数据</param> public override void BulkInsert<T>(List<T> entities) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString =_connectionString ; if (conn.State != ConnectionState.Open) { conn.Open(); } string tableName = string .Empty; var tableAttribute = typeof (T).GetCustomAttributes( typeof (TableAttribute), true ).FirstOrDefault(); if (tableAttribute != null ) tableName = ((TableAttribute)tableAttribute).Name; else tableName = typeof (T).Name; SqlBulkCopy sqlBC = new SqlBulkCopy(conn) { BatchSize = 100000, BulkCopyTimeout = 0, DestinationTableName = tableName }; using (sqlBC) { sqlBC.WriteToServer(entities.ToDataTable()); } } } public override DataTable GetDataTableWithSql( string sql) { return GetDataTableWithSql(sql); } public override DataTable GetDataTableWithSql( string sql, List<DbParameter> spList= null ) { DataTable dt = new DataTable(); ; using (SqlConnection conn = new SqlConnection(_connectionString)) { SqlDataAdapter da = new SqlDataAdapter(sql, conn); da.SelectCommand.CommandType = CommandType.Text; if (spList.ToArray() != null ) { da.SelectCommand.Parameters.AddRange(spList.ToArray()); } da.Fill(dt); } return dt; } #endregion } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下