書接上文,繼續搭建我們基於.netCore 的開發框架。首先是我們的項目分層結構。 這個分層結構,是參考張老師的分層結構,但是實際項目中,我沒有去實現倉儲模型。因為我使用的是EFCore ,最近也一直在想,EFCore 在我們的架構體系中到底扮演著什麼樣的角色?? 當然,實現倉儲層,也有他的好處,如 ...
書接上文,繼續搭建我們基於.netCore 的開發框架。首先是我們的項目分層結構。
這個分層結構,是參考張老師的分層結構,但是實際項目中,我沒有去實現倉儲模型。因為我使用的是EFCore ,最近也一直在想,EFCore 在我們的架構體系中到底扮演著什麼樣的角色??
當然,實現倉儲層,也有他的好處,如果真的以後要更換ORM框架的時候,不用去更改服務層邏輯,不用直接在倉儲裡面做更改就可以了。但是對於小項目,可能運行個十年都不會換資料庫,不會換ORM的項目,倉儲層的意義在哪?
希望對此有自己想法的朋友一起討論。在本系列里,我將保留倉儲層。
上面的分層結構,很容易就搭建好了,但是基於.NetCore 的項目,可能最主要的一點就是如何利用好DI,怎麼來實現依賴註入。
依照上圖中的依賴關係,我們以此構建自己相應層級中的內容。
分別在IRepository和Repository項目下,新建Base文件夾,並分別建立IBaseRepository和BaseRepository
具體代碼如下:
IBaseRepository.cs:
1 using Sincere.Core.Model; 2 using System; 3 using System.Collections.Generic; 4 using System.Data; 5 using System.Data.SqlClient; 6 using System.Linq.Expressions; 7 using System.Text; 8 using System.Threading.Tasks; 9 10 namespace Sincere.Core.IRepository.Base 11 { 12 public interface IBaseRepository<TEntity> where TEntity : class 13 { 14 Task<int> Execute(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text); 15 Task<List<TEntity>> Query(string sql, List<SqlParameter> parms, CommandType cmdType = CommandType.Text); 16 Task<bool> Insert(TEntity model); 17 Task<bool> InsertRange(List<TEntity> datas); 18 19 Task<int> Del(TEntity model); 20 21 Task<int> DelBy(Expression<Func<TEntity, bool>> delWhere); 22 23 Task<int> Modify(TEntity model); 24 25 Task<int> Modify(TEntity model, params string[] propertyNames); 26 27 Task<int> ModifyBy(TEntity model, Expression<Func<TEntity, bool>> whereLambda, params string[] modifiedPropertyNames); 28 29 Task<List<TEntity>> GetList(); 30 31 Task<List<TEntity>> GetListBy(Expression<Func<TEntity, bool>> whereLambda); 32 33 Task<TEntity> GetModelById(Expression<Func<TEntity, bool>> whereLambda); 34 35 Task<List<TEntity>> GetListBy<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true); 36 37 Task<List<TEntity>> GetListBy<TKey>(int top, Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true); 38 39 Task<List<TEntity>> GetListBy<TKey1, TKey2>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey1>> orderLambda1, Expression<Func<TEntity, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true); 40 41 Task<List<TEntity>> GetListBy<TKey1, TKey2>(int top, Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey1>> orderLambda1, Expression<Func<TEntity, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true); 42 43 Task<List<TEntity>> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true); 44 45 Task<PageModel<TEntity>> GetPagedList<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderByLambda, bool isAsc = true, int pageIndex = 1, int pageSize = 20); 46 47 void RollBackChanges(); 48 49 } 50 }View Code
BaseRepository.cs:
1 using Microsoft.EntityFrameworkCore; 2 using Sincere.Core.IRepository.Base; 3 using Sincere.Core.Model; 4 using Sincere.Core.Model.Models; 5 using System; 6 using System.Collections.Generic; 7 using System.Data; 8 using System.Data.SqlClient; 9 using System.Linq; 10 using System.Linq.Expressions; 11 using System.Reflection; 12 using System.Text; 13 using System.Threading.Tasks; 14 15 namespace Sincere.Core.Repository.Base 16 { 17 public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new() 18 { 19 private BaseCoreContext _db; 20 private readonly DbSet<TEntity> _dbSet; 21 22 internal BaseCoreContext Db 23 { 24 get { return _db; } 25 private set { _db = value; } 26 } 27 public BaseRepository(IBaseContext mydbcontext) 28 { 29 this._db = mydbcontext as BaseCoreContext; 30 this._dbSet = _db.Set<TEntity>(); 31 } 32 33 #region INSERT 34 35 /// <summary> 36 /// 新增 實體 37 /// </summary> 38 /// <param name="model"></param> 39 /// <returns></returns> 40 //public async Task<bool> Insert(TEntity model, bool isSaveChanges = false) 41 public async Task<bool> Insert(TEntity model) 42 { 43 _db.Set<TEntity>().Add(model); 44 //if (isSaveChanges) 45 //{ 46 return await _db.SaveChangesAsync() > 0; 47 //} 48 //else 49 //{ 50 // return false; 51 //} 52 53 } 54 55 /// <summary> 56 /// 普通批量插入 57 /// </summary> 58 /// <param name="datas"></param> 59 public async Task<bool> InsertRange(List<TEntity> datas) 60 { 61 await _db.Set<TEntity>().AddRangeAsync(datas); 62 return await _db.SaveChangesAsync() == datas.Count; 63 } 64 65 #endregion INSERT 66 67 #region Delete 68 69 #region 2.0 根據id刪除 + int Del(T model) 70 /// <summary> 71 /// 2.0 根據id刪除 72 /// </summary> 73 /// <param name="model">必須包含要刪除id的對象</param> 74 /// <returns></returns> 75 public async Task<int> Del(TEntity model) 76 { 77 _db.Set<TEntity>().Attach(model); 78 _db.Set<TEntity>().Remove(model); 79 return await _db.SaveChangesAsync(); 80 } 81 #endregion 82 83 #region 2.1 根據條件刪除 + int DelBy(Expression<Func<T, bool>> delWhere) 84 /// <summary> 85 /// 2.1 根據條件刪除 86 /// </summary> 87 /// <param name="delWhere"></param> 88 /// <returns>返回受影響的行數</returns> 89 public async Task<int> DelBy(Expression<Func<TEntity, bool>> delWhere) 90 { 91 //2.1.1 查詢要刪除的數據 92 List<TEntity> listDeleting = _db.Set<TEntity>().Where(delWhere).ToList(); 93 //2.1.2 將要刪除的數據 用刪除方法添加到 EF 容器中 94 listDeleting.ForEach(u => 95 { 96 _db.Set<TEntity>().Attach(u); //先附加到EF 容器 97 _db.Set<TEntity>().Remove(u); //標識為刪除狀態 98 }); 99 //2.1.3 一次性生成sql語句 到資料庫執行刪除 100 return await _db.SaveChangesAsync(); 101 } 102 #endregion 103 104 105 #endregion 106 107 #region UPDATE 108 109 #region 3.0 修改實體 + int Modify(T model) 110 /// <summary> 111 /// 修改實體 112 /// </summary> 113 /// <param name="model"></param> 114 /// <returns></returns> 115 public async Task<int> Modify(TEntity model) 116 { 117 //EntityEntry entry = _db.Entry<TEntity>(model); 118 _db.Set<TEntity>().Update(model); 119 return await _db.SaveChangesAsync(); 120 } 121 #endregion 122 123 #region 3.1 修改實體,可修改指定屬性 + int Modify(T model, params string[] propertyNames) 124 /// <summary> 125 /// 3.1 修改實體,可修改指定屬性 126 /// </summary> 127 /// <param name="model"></param> 128 /// <param name="propertyName"></param> 129 /// <returns></returns> 130 public async Task<int> Modify(TEntity model, params string[] propertyNames) 131 { 132 //3.1.1 將對象添加到EF中 133 EntityEntry entry = _db.Entry<TEntity>(model); 134 //3.1.2 先設置對象的包裝狀態為 Unchanged 135 entry.State = EntityState.Unchanged; 136 //3.1.3 迴圈被修改的屬性名數組 137 foreach (string propertyName in propertyNames) 138 { 139 //將每個被修改的屬性的狀態設置為已修改狀態;這樣在後面生成的修改語句時,就只為標識為已修改的屬性更新 140 entry.Property(propertyName).IsModified = true; 141 } 142 return await _db.SaveChangesAsync(); 143 } 144 #endregion 145 146 #region 3.2 批量修改 + int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedPropertyNames) 147 /// <summary> 148 /// 3.2 批量修改 149 /// </summary> 150 /// <param name="model"></param> 151 /// <param name="whereLambda"></param> 152 /// <param name="modifiedPropertyNames"></param> 153 /// <returns></returns> 154 public async Task<int> ModifyBy(TEntity model, Expression<Func<TEntity, bool>> whereLambda, params string[] modifiedPropertyNames) 155 { 156 //3.2.1 查詢要修改的數據 157 List<TEntity> listModifing = _db.Set<TEntity>().Where(whereLambda).ToList(); 158 //3.2.2 獲取實體類類型對象 159 Type t = typeof(TEntity); 160 //3.2.3 獲取實體類所有的公共屬性 161 List<PropertyInfo> propertyInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); 162 //3.2.4 創建實體屬性字典集合 163 Dictionary<string, PropertyInfo> dicPropertys = new Dictionary<string, PropertyInfo>(); 164 //3.2.5 將實體屬性中要修改的屬性名 添加到字典集合中 鍵:屬性名 值:屬性對象 165 propertyInfos.ForEach(p => 166 { 167 if (modifiedPropertyNames.Contains(p.Name)) 168 { 169 dicPropertys.Add(p.Name, p); 170 } 171 }); 172 //3.2.6 迴圈要修改的屬性名 173 foreach (string propertyName in modifiedPropertyNames) 174 { 175 //判斷要修改的屬性名是否在實體類的屬性集合中存在 176 if (dicPropertys.ContainsKey(propertyName)) 177 { 178 //如果存在,則取出要修改的屬性對象 179 PropertyInfo proInfo = dicPropertys[propertyName]; 180 //取出要修改的值 181 object newValue = proInfo.GetValue(model, null); 182 //批量設置要修改對象的屬性 183 foreach (TEntity item in listModifing) 184 { 185 //為要修改的對象的要修改的屬性設置新的值 186 proInfo.SetValue(item, newValue, null); 187 } 188 } 189 } 190 //一次性生成sql語句 到資料庫執行 191 return await _db.SaveChangesAsync(); 192 } 193 #endregion 194 195 196 #endregion UPDATE 197 198 #region SELECT 199 200 #region 5.0 根據條件查詢 + List<TEntity> GetListBy(Expression<Func<T, bool>> whereLambda) 201 /// <summary> 202 /// 5.0 根據條件查詢 203 /// </summary> 204 /// <param name="whereLambda"></param> 205 /// <returns></returns> 206 public async Task<List<TEntity>> GetListBy(Expression<Func<TEntity, bool>> whereLambda) 207 { 208 return await _db.Set<TEntity>().Where(whereLambda).AsNoTracking().ToListAsync(); 209 } 210 211 public async Task<TEntity> GetModelById(Expression<Func<TEntity, bool>> whereLambda) 212 { 213 return await _db.Set<TEntity>().Where(whereLambda).AsNoTracking().FirstOrDefaultAsync(); 214 } 215 public async Task<List<TEntity>> GetList() 216 { 217 return await _db.Set<TEntity>().AsNoTracking().ToListAsync(); 218 } 219 #endregion 220 221 #region 5.1 根據條件查詢,併排序 + List<TEntity> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true) 222 /// <summary> 223 /// 5.1 根據條件查詢,併排序 224 /// </summary> 225 /// <typeparam name="TKey"></typeparam> 226 /// <param name="whereLambda"></param> 227 /// <param name="orderLambda"></param> 228 /// <param name="isAsc"></param> 229 /// <returns></returns> 230 public async Task<List<TEntity>> GetListBy<TKey>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true) 231 { 232 if (isAsc) 233 { 234 return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda).AsNoTracking().ToListAsync(); 235 } 236 else 237 { 238 return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda).AsNoTracking().ToListAsync(); 239 } 240 } 241 #endregion 242 243 #region 5.2 根據條件查詢Top多少個,併排序 + List<TEntity> GetListBy<TKey>(int top, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderLambda, bool isAsc = true) 244 /// <summary> 245 /// 5.2 根據條件查詢Top多少個,併排序 246 /// </summary> 247 /// <typeparam name="TKey"></typeparam> 248 /// <param name="top"></param> 249 /// <param name="whereLambda"></param> 250 /// <param name="orderLambda"></param> 251 /// <param name="isAsc"></param> 252 /// <returns></returns> 253 public async Task<List<TEntity>> GetListBy<TKey>(int top, Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey>> orderLambda, bool isAsc = true) 254 { 255 if (isAsc) 256 { 257 return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda).Take(top).AsNoTracking().ToListAsync(); 258 } 259 else 260 { 261 return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda).Take(top).AsNoTracking().ToListAsync(); 262 } 263 } 264 #endregion 265 266 #region 5.3 根據條件排序查詢 雙排序 + List<TEntity> GetListBy<TKey1, TKey2>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey1>> orderLambda1, Expression<Func<T, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true) 267 /// <summary> 268 /// 5.3 根據條件排序查詢 雙排序 269 /// </summary> 270 /// <typeparam name="TKey1"></typeparam> 271 /// <typeparam name="TKey2"></typeparam> 272 /// <param name="whereLambda"></param> 273 /// <param name="orderLambda1"></param> 274 /// <param name="orderLambda2"></param> 275 /// <param name="isAsc1"></param> 276 /// <param name="isAsc2"></param> 277 /// <returns></returns> 278 public async Task<List<TEntity>> GetListBy<TKey1, TKey2>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey1>> orderLambda1, Expression<Func<TEntity, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true) 279 { 280 if (isAsc1) 281 { 282 if (isAsc2) 283 { 284 return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda1).ThenBy(orderLambda2).AsNoTracking().ToListAsync(); 285 } 286 else 287 { 288 return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda1).ThenByDescending(orderLambda2).AsNoTracking().ToListAsync(); 289 } 290 } 291 else 292 { 293 if (isAsc2) 294 { 295 return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda1).ThenBy(orderLambda2).AsNoTracking().ToListAsync(); 296 } 297 else 298 { 299 return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda1).ThenByDescending(orderLambda2).AsNoTracking().ToListAsync(); 300 } 301 } 302 } 303 #endregion 304 305 #region 5.3 根據條件排序查詢Top個數 雙排序 + List<TEntity> GetListBy<TKey1, TKey2>(int top, Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, TKey1>> orderLambda1, Expression<Func<T, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true) 306 /// <summary> 307 /// 5.3 根據條件排序查詢Top個數 雙排序 308 /// </summary> 309 /// <typeparam name="TKey1"></typeparam> 310 /// <typeparam name="TKey2"></typeparam> 311 /// <param name="top"></param> 312 /// <param name="whereLambda"></param> 313 /// <param name="orderLambda1"></param> 314 /// <param name="orderLambda2"></param> 315 /// <param name="isAsc1"></param> 316 /// <param name="isAsc2"></param> 317 /// <returns></returns> 318 public async Task<List<TEntity>> GetListBy<TKey1, TKey2>(int top, Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TKey1>> orderLambda1, Expression<Func<TEntity, TKey2>> orderLambda2, bool isAsc1 = true, bool isAsc2 = true) 319 { 320 if (isAsc1) 321 { 322 if (isAsc2) 323 { 324 return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda1).ThenBy(orderLambda2).Take(top).AsNoTracking().ToListAsync(); 325 } 326 else 327 { 328 return await _db.Set<TEntity>().Where(whereLambda).OrderBy(orderLambda1).ThenByDescending(orderLambda2).Take(top).AsNoTracking().ToListAsync(); 329 } 330 } 331 else 332 { 333 if (isAsc2) 334 { 335 return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda1).ThenBy(orderLambda2).Take(top).AsNoTracking().ToListAsync(); 336 } 337 else 338 { 339 return await _db.Set<TEntity>().Where(whereLambda).OrderByDescending(orderLambda1).ThenByDescending(orderLambda2).Take(top).AsNoTracking().ToListAsync(); 340 } 341 } 342 } 343 #endregion 344 345 #endregion SELECT 346 347 #region 分頁 348 349 #region 6.0 分頁查詢 + List<T> GetPagedList<TKey> 350 /// <summary> 351 /// 分頁查詢 + List<TEntity> GetPagedList 352 /// </summary> 353 /// <typeparam name="TKey"></typeparam> 354 /// <param name="pageIndex">頁碼</param> 355 /// <param name="pageSize">頁容量</param> 356 /// <param name="whereLambda">條件 lambda表達式