1 /// <summary> 2 /// 在数据仓储的情况下进一步封装数据库基础操作,此版本为异步版本 Created by ZhangQC 2016.08.17 3 /// </summary> 4 public static partial class EntityExtend 5 { 6 /// <summary> 7 /// 日志 8 /// </summary> 9 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 10 11 #region 数据库查询 12 13 /// <summary> 14 /// 根据实体和条件获取数据库对应表 Created by ZhangQC 2016.08.17 15 /// </summary> 16 /// <typeparam name="T">泛指Entity</typeparam> 17 /// <param name="entity">数据库实体</param> 18 /// <param name="where">查询条件</param> 19 /// <returns></returns> 20 public static async Task<IEnumerable<T>> GetTableAsync<T>(this T entity, Expression<Func<T, bool>> where = null) where T : class 21 { 22 return await Task.Run(() => 23 { 24 try 25 { 26 using (var db = new Repository<T>(new EFContext().ContextRead)) 27 { 28 return @where != null ? db.DoQuery(@where).ToList() : db.DoQuery().ToList(); 29 } 30 } 31 catch (Exception ex) 32 { 33 Log.ErrorFormat("根据实体和条件获取数据库对应表出错:{0}", ex); 34 throw new ApplicationException("数据库查询失败"); 35 } 36 }); 37 } 38 39 /// <summary> 40 /// 获取表总数 41 /// </summary> 42 /// <typeparam name="T"></typeparam> 43 /// <param name="entity"></param> 44 /// <param name="where"></param> 45 /// <returns></returns> 46 public static async Task<int> GetCount<T>(this T entity, Expression<Func<T, bool>> where = null) where T : class 47 { 48 return await Task.Run(() => 49 { 50 try 51 { 52 using (var db = new Repository<T>(new EFContext().ContextRead)) 53 { 54 return @where != null ? db.DoQuery(@where).Count() : db.DoQuery().Count(); 55 } 56 } 57 catch (Exception ex) 58 { 59 Log.ErrorFormat("获取表总数量出错:{0}", ex); 60 throw new ApplicationException("数据库查询失败"); 61 } 62 }); 63 } 64 65 66 /// <summary> 67 /// 查询数据,支持分页,排序,过滤操作 倒叙 68 /// </summary> 69 /// <remarks>"此方法完全是为了兼容MVCPager定制,不属于框架部分"</remarks> 70 /// <returns></returns> 71 public static async Task<PagedList<T>> GetTableBySortDescPageListAsync<T>(this T entity, int pageIndex, int pageSize, Expression<Func<T, bool>> where = null, 72 Expression<Func<T, object>> sort = null) where T : class 73 { 74 return await Task.Run(() => 75 { 76 try 77 { 78 using (var db = new Repository<T>(new EFContext().ContextRead)) 79 { 80 var table = @where != null 81 ? db.DoQuery(@where) 82 : db.DoQuery(); 83 //如果排序为null,那么就按实体其中的一个主键进行排序 84 if (sort == null) 85 { 86 var entitySet = db.EntitySet<T>(); 87 var keyCollections = entitySet.ElementType.KeyMembers; 88 if (keyCollections.FirstOrDefault() == null) 89 { 90 throw new ApplicationException("要查询的表没有发现主键!"); 91 } 92 //自动生成主键排序字段 93 var entityKey = keyCollections.Aggregate(string.Empty, (a, b) => a + b + " desc,").TrimEnd(','); 94 //排序后的IQuaryable 95 var tableSortNull = table.OrderUsingSortExpression(entityKey); 96 return tableSortNull.ToPagedList(pageIndex, pageSize); 97 } 98 var tableSort = table.OrderBy(@sort); 99 return tableSort.ToPagedList(pageIndex, pageSize); 100 } 101 } 102 catch (Exception ex) 103 { 104 Log.ErrorFormat("对指定实体进行查询,可以分页,可以排序出错:{0}", ex); 105 throw new ApplicationException("数据库查询失败"); 106 } 107 }); 108 } 109 110 /// <summary> 111 /// 查询数据,支持分页,排序,过滤操作 正叙 112 /// </summary> 113 /// <remarks>"此方法完全是为了兼容MVCPager定制,不属于框架部分"</remarks> 114 /// <returns></returns> 115 public static async Task<PagedList<T>> GetTableBySortAscPageListAsync<T>(this T entity, int pageIndex, int pageSize, Expression<Func<T, bool>> where = null, 116 Expression<Func<T, object>> sort = null) where T : class 117 { 118 return await Task.Run(() => 119 { 120 try 121 { 122 using (var db = new Repository<T>(new EFContext().ContextRead)) 123 { 124 var table = @where != null 125 ? db.DoQuery(@where) 126 : db.DoQuery(); 127 //如果排序为null,那么就按实体其中的一个主键进行排序 128 if (sort == null) 129 { 130 var entitySet = db.EntitySet<T>(); 131 var keyCollections = entitySet.ElementType.KeyMembers; 132 if (keyCollections.FirstOrDefault() == null) 133 { 134 throw new ApplicationException("要查询的表没有发现主键!"); 135 } 136 //自动生成主键排序字段 137 var entityKey = 138 keyCollections.Aggregate(string.Empty, (a, b) => a + b + " asc,").TrimEnd(','); 139 140 #region 注释代码,警醒用 141 142 //主键类型 143 //var type = ((EdmProperty) keyCollections).PrimitiveType.ClrEquivalentType; 144 //创建实例 145 //var entityActivator = Activator.CreateInstance<T>(); 146 ////创建类型实例 147 //var tKeyActivator = Activator.CreateInstance(type); 148 149 #endregion 150 151 //排序后的IQuaryable 152 var tableSortNull = table.OrderUsingSortExpression(entityKey); 153 return tableSortNull.ToPagedList(pageIndex, pageSize); 154 } 155 var tableSort = table.OrderBy(@sort); 156 return tableSort.ToPagedList(pageIndex, pageSize); 157 } 158 } 159 catch (Exception ex) 160 { 161 Log.ErrorFormat("对指定实体进行查询,可以分页,可以排序出错:{0}", ex); 162 throw new ApplicationException("数据库查询失败"); 163 } 164 }); 165 } 166 167 168 169 /// <summary> 170 /// 根据实体和条件获取数据库对应表 Created by ZhangQC 2016.08.17 171 /// </summary> 172 /// <typeparam name="T">泛指Entity</typeparam> 173 /// <param name="entity">数据库实体</param> 174 /// <param name="where">查询条件</param> 175 /// <returns></returns> 176 public static async Task<T> GetTableSingleAsync<T>(this T entity, Expression<Func<T, bool>> where = null) where T : class 177 { 178 return await Task.Run(() => 179 { 180 try 181 { 182 using (var db = new Repository<T>(new EFContext().ContextRead)) 183 { 184 return @where != null ? db.DoQuery(@where).FirstOrDefault() : db.DoQuery().FirstOrDefault(); 185 } 186 } 187 catch (Exception ex) 188 { 189 Log.ErrorFormat("根据实体和条件获取数据库对应表出错:{0}", ex); 190 throw new ApplicationException("数据库查询失败"); 191 } 192 }); 193 } 194 195 196 197 198 /// <summary> 199 /// 根据实体和条件查询数据库对应表加排序功能 Created by ZhangQC 2016.08.17 200 /// </summary> 201 /// <typeparam name="T">泛指实体</typeparam> 202 /// <param name="entity">数据库实体</param> 203 /// <param name="where">泛指查询条件表达式</param> 204 /// <param name="sort">泛指排序表达式</param> 205 /// <returns></returns> 206 public static async Task<IEnumerable<T>> GetTableBySortAsync<T>(this T entity, Expression<Func<T, bool>> where = null, 207 Func<T, object> sort = null) where T : class 208 { 209 try 210 { 211 var table = await entity.GetTableAsync(@where); 212 return @sort != null ? table.OrderBy(@sort).ToList() : table.ToList(); 213 } 214 catch (Exception ex) 215 { 216 Log.ErrorFormat("根据实体和条件查询数据库对应表加排序功能出错:{0}", ex); 217 throw new ApplicationException("数据库查询失败"); 218 } 219 } 220 221 222 /// <summary> 223 /// 根据实体和条件查询数据库对应表加排序功能 Created by ZhangQC 2016.08.17 224 /// </summary> 225 /// <typeparam name="T">泛指实体</typeparam> 226 /// <param name="entity">数据库实体</param> 227 /// <param name="where">泛指查询条件表达式</param> 228 /// <param name="sort">泛指排序表达式</param> 229 /// <returns></returns> 230 public static async Task<IEnumerable<T>> GetTableBySortDescAsync<T>(this T entity, Expression<Func<T, bool>> where = null, 231 Func<T, object> sort = null) where T : class 232 { 233 try 234 { 235 var table = await entity.GetTableAsync(@where); 236 return @sort != null ? table.OrderByDescending(@sort).ToList() : table.ToList(); 237 } 238 catch (Exception ex) 239 { 240 Log.ErrorFormat("根据实体和条件查询数据库对应表加排序功能出错:{0}", ex); 241 throw new ApplicationException("数据库查询失败"); 242 } 243 } 244 245 246 247 /// <summary> 248 /// 对指定实体进行查询,可以分页,可以排序 Created by ZhangQC 2016.08.17 249 /// </summary> 250 /// <typeparam name="T">泛指实体</typeparam> 251 /// <param name="entity">数据库实体</param> 252 /// <param name="skip">从多少条开始</param> 253 /// <param name="take">共取多少条</param> 254 /// <param name="where">泛指查询条件表达式</param> 255 /// <param name="sort">泛指排序表达式</param> 256 /// <returns></returns> 257 public static async Task<IEnumerable<T>> GetTableBySoryPageAsync<T>(this T entity, int? skip, int? take, Expression<Func<T, bool>> where = null, 258 Expression<Func<T, object>> sort = null) where T : class 259 { 260 return await Task.Run(() => 261 { 262 try 263 { 264 using (var db = new Repository<T>(new EFContext().ContextRead)) 265 { 266 var table = @where != null 267 ? db.DoQuery(@where) 268 : db.DoQuery(); 269 if (@skip == null || @take == null) 270 return @sort != null ? table.OrderBy(@sort).ToList() : table.ToList(); 271 //如果排序为null,那么就按实体其中的一个主键进行排序 272 if (sort == null) 273 { 274 var entitySet = db.EntitySet<T>(); 275 var keyCollections = entitySet.ElementType.KeyMembers; 276 if (keyCollections.FirstOrDefault() == null) 277 { 278 throw new ApplicationException("要查询的表没有发现主键!"); 279 } 280 //自动生成主键排序字段 281 var entityKey = keyCollections.Aggregate(string.Empty, (a, b) => a + b + " asc,").TrimEnd(','); 282 //排序后的IQuaryable 283 var tableSortNull = table.OrderUsingSortExpression(entityKey); 284 return tableSortNull.Skip((int)@skip).Take((int)@take).ToList(); 285 } 286 var tableSort = table.OrderBy(@sort); 287 return tableSort.Skip((int)@skip).Take((int)@take).ToList(); 288 } 289 } 290 catch (Exception ex) 291 { 292 Log.ErrorFormat("对指定实体进行查询,可以分页,可以排序出错:{0}", ex); 293 throw new ApplicationException("数据库查询失败"); 294 } 295 }); 296 } 297 /// <summary> 298 /// 对指定实体进行查询,可以分页,可以排序 倒序 Created by ZhangQC 2016.08.17 299 /// </summary> 300 /// <typeparam name="T"></typeparam> 301 /// <param name="entity"></param> 302 /// <param name="skip"></param> 303 /// <param name="take"></param> 304 /// <param name="where"></param> 305 /// <param name="sort"></param> 306 /// <returns></returns> 307 public static async Task<IEnumerable<T>> GetTableBySoryDescPageAsync<T>(this T entity, int? skip, int? take, Expression<Func<T, bool>> where = null, 308 Expression<Func<T, object>> sort = null) where T : class 309 { 310 return await Task.Run(() => 311 { 312 try 313 { 314 using (var db = new Repository<T>(new EFContext().ContextRead)) 315 { 316 var table = @where != null 317 ? db.DoQuery(@where) 318 : db.DoQuery(); 319 if (@skip == null || @take == null) 320 return @sort != null ? table.OrderByDescending(@sort).ToList() : table.ToList(); 321 //如果排序为null,那么就按实体其中的一个主键进行排序 322 if (sort == null) 323 { 324 var entitySet = db.EntitySet<T>(); 325 var keyCollections = entitySet.ElementType.KeyMembers; 326 if (keyCollections.FirstOrDefault() == null) 327 { 328 throw new ApplicationException("要查询的表没有发现主键!"); 329 } 330 //自动生成主键排序字段 331 var entityKey = keyCollections.Aggregate(string.Empty, (a, b) => a + b + " desc,").TrimEnd(','); 332 //排序后的IQuaryable 333 var tableSortNull = table.OrderUsingSortExpression(entityKey); 334 return tableSortNull.Skip((int)@skip).Take((int)@take).ToList(); 335 } 336 var tableSort = table.OrderBy(@sort); 337 return tableSort.Skip((int)@skip).Take((int)@take).ToList(); 338 } 339 } 340 catch (Exception ex) 341 { 342 Log.ErrorFormat("对指定实体进行查询,可以分页,可以排序出错:{0}", ex); 343 throw new ApplicationException("数据库查询失败"); 344 } 345 }); 346 } 347 348 #endregion 349 350 #region 保存数据 351 /// <summary> 352 /// 单个实体保存数据库时使用 Created by ZhangQC 2016.08.17 353 /// </summary> 354 /// <typeparam name="T"></typeparam> 355 /// <param name="entity"></param> 356 /// <returns></returns> 357 public static async Task<bool> SaveAsync<T>(this T entity) where T : class 358 { 359 return await Task.Run(() => 360 { 361 try 362 { 363 using (var db = new Repository<T>(new EFContext().ContextRead)) 364 { 365 db.Add(entity); 366 return db.Save() != 0; 367 } 368 } 369 catch (Exception ex) 370 { 371 Log.ErrorFormat("单个实体保存数据库时使用出错:{0}", ex); 372 return false; 373 } 374 }); 375 } 376 377 378 379 /// <summary> 380 /// 实体集合新增或者更新数据库时使用 Created by ZhangQC 2016.08.17 381 /// </summary> 382 /// <typeparam name="T"></typeparam> 383 /// <param name="entityList"></param> 384 /// <returns></returns> 385 public static async Task<bool> SaveAsync<T>(this List<T> entityList) where T : class 386 { 387 return await Task.Run(() => 388 { 389 try 390 { 391 using (var db = new Repository<T>(new EFContext().ContextRead)) 392 { 393 db.AddOrUpdate(entityList.ToArray()); 394 db.Save(); 395 return true; 396 } 397 } 398 catch (Exception ex) 399 { 400 Log.ErrorFormat("实体集合新增或者更新数据库时使用:{0}", ex); 401 return false; 402 } 403 }); 404 } 405 #endregion 406 407 408 #region 更新操作 409 /// <summary> 410 /// 更新实体数据(批量可以使用Sava(List《T》)方法) Created by ZhangQC 2016.08.17 411 /// </summary> 412 /// <typeparam name="T"></typeparam> 413 /// <param name="entity"></param> 414 /// <returns></returns> 415 public static async Task<bool> UpdateAsync<T>(this T entity) where T : class 416 { 417 return await Task.Run(() => 418 { 419 try 420 { 421 using (var db = new Repository<T>(new EFContext().ContextRead)) 422 { 423 db.Update(entity); 424 return db.Save() != 0; 425 } 426 } 427 catch (Exception ex) 428 { 429 Log.ErrorFormat("更新实体数据(批量可以使用Sava(List《T》)方法)出错:{0}", ex); 430 return false; 431 } 432 }); 433 } 434 #endregion 435 436 #region 删除操作 437 /// <summary> 438 /// 删除操作 Created by ZhangQC 2016.08.17 439 /// </summary> 440 /// <typeparam name="T"></typeparam> 441 /// <param name="entity"></param> 442 /// <returns></returns> 443 public static async Task<bool> DeleteAsync<T>(this T entity) where T : class 444 { 445 return await Task.Run(() => 446 { 447 try 448 { 449 using (var db = new Repository<T>(new EFContext().ContextRead)) 450 { 451 db.Delete(entity); 452 return db.Save() != 0; 453 } 454 } 455 catch (Exception ex) 456 { 457 Log.ErrorFormat("出错:{0}", ex); 458 return false; 459 } 460 }); 461 } 462 463 /// <summary> 464 /// 删除操作 Created by ZhangQC 2016.08.17 465 /// </summary> 466 /// <typeparam name="T"></typeparam> 467 /// <param name="entity"></param> 468 /// <returns></returns> 469 public static async Task<bool> DeleteAsync<T>(this IQueryable<T> entity) where T : class 470 { 471 return await Task.Run(() => 472 { 473 try 474 { 475 using (var db = new Repository<T>(new EFContext().ContextRead)) 476 { 477 db.Delete(entity); 478 return db.Save() != 0; 479 } 480 } 481 catch (Exception ex) 482 { 483 Log.ErrorFormat("出错:{0}", ex); 484 return false; 485 } 486 }); 487 } 488 489 490 /// <summary> 491 /// 批量删除操作 Created by ZhangQC 2016.08.17 492 /// </summary> 493 /// <typeparam name="T"></typeparam> 494 /// <param name="entity"></param> 495 /// <returns></returns> 496 public static async Task<bool> DeleteAsync<T>(this IEnumerable<T> entity) where T : class 497 { 498 return await Task.Run(() => 499 { 500 try 501 { 502 using (var db = new Repository<T>(new EFContext().ContextRead)) 503 { 504 db.Delete(entity); 505 return db.Save() != 0; 506 } 507 } 508 catch (Exception ex) 509 { 510 Log.ErrorFormat("出错:{0}", ex); 511 return false; 512 } 513 }); 514 } 515 516 517 #endregion 518 }