飞星
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

723 satır
24 KiB

  1. using Permission.Infrastructure.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data.Common;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Threading.Tasks;
  8. using Microsoft.EntityFrameworkCore;
  9. using System.Reflection;
  10. using Permission.Infrastructure.WebControls;
  11. using Permission.Entity.DbContext;
  12. using Permission.Infrastructure.Repositories;
  13. namespace Permission.Data.Repositories
  14. {
  15. /// <summary>
  16. /// 仓储数据访问基接口实现
  17. /// </summary>
  18. /// <typeparam name="T"></typeparam>
  19. public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
  20. {
  21. #region 数据上下文
  22. /// <summary>
  23. /// 数据上下文
  24. /// </summary>
  25. private readonly PermissionContext _context;
  26. /// <summary>
  27. /// 工作单元
  28. /// </summary>
  29. private IUnitOfWork _unitOfWork;
  30. public IQueryable<T> Entities => _context.Set<T>();
  31. public BaseRepository(PermissionContext context, IUnitOfWork unitOfWork)
  32. {
  33. _context = context;
  34. _unitOfWork = unitOfWork;
  35. }
  36. #endregion
  37. #region 单模型 CRUD 操作
  38. public virtual bool Save(T entity, bool isCommit = true)
  39. {
  40. _context.Add(entity);
  41. if (isCommit)
  42. {
  43. return _unitOfWork.SaveChanges() > 0;
  44. }
  45. else
  46. {
  47. return false;
  48. }
  49. }
  50. public virtual async Task<bool> SaveAsync(T entity, bool isCommit = true)
  51. {
  52. _context.Set<T>().Add(entity);
  53. if (isCommit)
  54. {
  55. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  56. }
  57. else
  58. {
  59. return await Task.Run(() => false);
  60. }
  61. }
  62. public virtual bool Update(T entity, bool isCommit = true)
  63. {
  64. if (_context.Entry(entity).State == EntityState.Detached)
  65. {
  66. _context.Set<T>().Attach(entity);
  67. _context.Entry(entity).State = EntityState.Modified;
  68. }
  69. else
  70. {
  71. _context.Entry(entity).State = EntityState.Modified;
  72. }
  73. if (isCommit)
  74. {
  75. return _unitOfWork.SaveChanges() > 0;
  76. }
  77. else
  78. {
  79. return false;
  80. }
  81. }
  82. public virtual async Task<bool> UpdateAsync(T entity, bool isCommit = true)
  83. {
  84. //_context.Set<T>().Attach(entity);
  85. //_context.Entry<T>(entity).State = EntityState.Modified;
  86. if (_context.Entry(entity).State == EntityState.Detached)
  87. {
  88. _context.Set<T>().Attach(entity);
  89. _context.Entry(entity).State = EntityState.Modified;
  90. }
  91. else
  92. {
  93. _context.Entry(entity).State = EntityState.Modified;
  94. }
  95. if (isCommit)
  96. {
  97. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  98. }
  99. else
  100. {
  101. return await Task.Run(() => false);
  102. }
  103. }
  104. public virtual bool SaveOrUpdate(T entity, bool isSave, bool isCommit = true)
  105. {
  106. return isSave ? Save(entity, isCommit) : Update(entity, isCommit);
  107. }
  108. public virtual async Task<bool> SaveOrUpdateAsync(T entity, bool isSave, bool isCommit = true)
  109. {
  110. return isSave ? await SaveAsync(entity, isCommit) : await UpdateAsync(entity, isCommit);
  111. }
  112. public virtual T Get(Expression<Func<T, bool>> predicate)
  113. {
  114. //return _context.Set<T>().AsNoTracking().SingleOrDefault(predicate);
  115. return _context.Set<T>().SingleOrDefault(predicate);
  116. }
  117. public virtual T Get(object key)
  118. {
  119. return _context.Set<T>().Find(key);
  120. }
  121. public virtual async Task<T> GetAsync(object key)
  122. {
  123. return await Task.Run(() => _context.Set<T>().Find(key));
  124. }
  125. public virtual async Task<T> GetAsync(Expression<Func<T, bool>> predicate)
  126. {
  127. return await Task.Run(() => _context.Set<T>().SingleOrDefault(predicate));
  128. }
  129. public virtual bool Delete(T entity, bool isCommit = true)
  130. {
  131. if (entity == null)
  132. {
  133. return false;
  134. }
  135. _context.Set<T>().Attach(entity);
  136. _context.Set<T>().Remove(entity);
  137. if (isCommit)
  138. {
  139. return _unitOfWork.SaveChanges() > 0;
  140. }
  141. else
  142. {
  143. return false;
  144. }
  145. }
  146. public virtual async Task<bool> DeleteAsync(T entity, bool isCommit = true)
  147. {
  148. if (entity == null)
  149. {
  150. return await Task.Run(() => false);
  151. }
  152. _context.Set<T>().Attach(entity);
  153. _context.Set<T>().Remove(entity);
  154. if (isCommit)
  155. {
  156. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  157. }
  158. else
  159. {
  160. return await Task.Run(() => false);
  161. }
  162. }
  163. #endregion
  164. #region 多模型 操作
  165. public virtual bool SaveList(List<T> entities, bool isCommit = true)
  166. {
  167. if (entities == null || !entities.Any())
  168. {
  169. return false;
  170. }
  171. entities.ToList().ForEach(item =>
  172. {
  173. _context.Set<T>().Add(item);
  174. });
  175. if (isCommit)
  176. {
  177. return _unitOfWork.SaveChanges() > 0;
  178. }
  179. else
  180. {
  181. return false;
  182. }
  183. }
  184. public virtual async Task<bool> SaveListAsync(List<T> entities, bool isCommit = true)
  185. {
  186. if (entities == null || !entities.Any())
  187. {
  188. return await Task.Run(() => false);
  189. }
  190. entities.ToList().ForEach(item =>
  191. {
  192. _context.Set<T>().Add(item);
  193. });
  194. if (isCommit)
  195. {
  196. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  197. }
  198. else
  199. {
  200. return await Task.Run(() => false);
  201. }
  202. }
  203. public virtual bool SaveList<TEntity>(List<TEntity> entities, bool isCommit = true) where TEntity : class
  204. {
  205. if (entities == null || !entities.Any())
  206. {
  207. return false;
  208. }
  209. var tmp = _context.ChangeTracker.Entries<T>().ToList();
  210. foreach (var x in tmp)
  211. {
  212. var properties = typeof(T).GetTypeInfo().GetProperties();
  213. foreach (var y in properties)
  214. {
  215. var entry = x.Property(y.Name);
  216. entry.CurrentValue = entry.OriginalValue;
  217. entry.IsModified = false;
  218. y.SetValue(x.Entity, entry.OriginalValue);
  219. }
  220. x.State = EntityState.Unchanged;
  221. }
  222. entities.ToList().ForEach(item =>
  223. {
  224. _context.Set<TEntity>().Add(item);
  225. });
  226. if (isCommit)
  227. {
  228. return _unitOfWork.SaveChanges() > 0;
  229. }
  230. else
  231. {
  232. return false;
  233. }
  234. }
  235. public virtual async Task<bool> SaveListAsync<TEntity>(List<TEntity> entities, bool isCommit = true) where TEntity : class
  236. {
  237. if (entities == null || !entities.Any())
  238. {
  239. return await Task.Run(() => false);
  240. }
  241. var tmp = _context.ChangeTracker.Entries<T>().ToList();
  242. foreach (var x in tmp)
  243. {
  244. var properties = typeof(T).GetTypeInfo().GetProperties();
  245. foreach (var y in properties)
  246. {
  247. var entry = x.Property(y.Name);
  248. entry.CurrentValue = entry.OriginalValue;
  249. entry.IsModified = false;
  250. y.SetValue(x.Entity, entry.OriginalValue);
  251. }
  252. x.State = EntityState.Unchanged;
  253. }
  254. entities.ToList().ForEach(item =>
  255. {
  256. _context.Set<TEntity>().Add(item);
  257. });
  258. if (isCommit)
  259. {
  260. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  261. }
  262. else
  263. {
  264. return await Task.Run(() => false);
  265. }
  266. }
  267. public virtual bool UpdateList(List<T> entities, bool isCommit = true)
  268. {
  269. if (entities == null || !entities.Any())
  270. {
  271. return false;
  272. }
  273. entities.ToList().ForEach(item =>
  274. {
  275. _context.Set<T>().Attach(item);
  276. _context.Entry<T>(item).State = EntityState.Modified;
  277. });
  278. if (isCommit)
  279. {
  280. return _unitOfWork.SaveChanges() > 0;
  281. }
  282. else
  283. {
  284. return false;
  285. }
  286. }
  287. public virtual async Task<bool> UpdateListAsync(List<T> entities, bool isCommit = true)
  288. {
  289. if (entities == null || !entities.Any())
  290. {
  291. return await Task.Run(() => false);
  292. }
  293. entities.ToList().ForEach(item =>
  294. {
  295. _context.Set<T>().Attach(item);
  296. _context.Entry<T>(item).State = EntityState.Modified;
  297. });
  298. if (isCommit)
  299. {
  300. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  301. }
  302. else
  303. {
  304. return await Task.Run(() => false);
  305. }
  306. }
  307. public virtual bool UpdateList<TEntity>(List<TEntity> entities, bool isCommit = true) where TEntity : class
  308. {
  309. if (entities == null || !entities.Any())
  310. {
  311. return false;
  312. }
  313. entities.ToList().ForEach(item =>
  314. {
  315. _context.Set<TEntity>().Attach(item);
  316. _context.Entry<TEntity>(item).State = EntityState.Modified;
  317. });
  318. if (isCommit)
  319. {
  320. return _unitOfWork.SaveChanges() > 0;
  321. }
  322. else
  323. {
  324. return false;
  325. }
  326. }
  327. public virtual async Task<bool> UpdateListAsync<TEntity>(List<TEntity> entities, bool isCommit = true) where TEntity : class
  328. {
  329. if (entities == null || !entities.Any())
  330. {
  331. return await Task.Run(() => false);
  332. }
  333. entities.ToList().ForEach(item =>
  334. {
  335. _context.Set<TEntity>().Attach(item);
  336. _context.Entry<TEntity>(item).State = EntityState.Modified;
  337. });
  338. if (isCommit)
  339. {
  340. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  341. }
  342. else
  343. {
  344. return await Task.Run(() => false);
  345. }
  346. }
  347. public virtual bool Delete(Expression<Func<T, bool>> predicate, bool isCommit = true)
  348. {
  349. IQueryable<T> entry = (predicate == null) ? _context.Set<T>().AsQueryable() : _context.Set<T>().Where(predicate);
  350. List<T> list = entry.ToList();
  351. if (list != null && list.Count == 0)
  352. {
  353. return false;
  354. }
  355. list.ForEach(item =>
  356. {
  357. _context.Set<T>().Attach(item);
  358. _context.Set<T>().Remove(item);
  359. });
  360. if (isCommit)
  361. {
  362. return _unitOfWork.SaveChanges() > 0;
  363. }
  364. else
  365. {
  366. return false;
  367. }
  368. }
  369. public virtual async Task<bool> DeleteAsync(Expression<Func<T, bool>> predicate, bool isCommit = true)
  370. {
  371. IQueryable<T> entry = (predicate == null) ? _context.Set<T>().AsQueryable() : _context.Set<T>().Where(predicate);
  372. List<T> list = entry.ToList();
  373. if (list != null && list.Count == 0)
  374. {
  375. return await Task.Run(() => false);
  376. }
  377. list.ForEach(item =>
  378. {
  379. _context.Set<T>().Attach(item);
  380. _context.Set<T>().Remove(item);
  381. });
  382. if (isCommit)
  383. {
  384. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  385. }
  386. else
  387. {
  388. return await Task.Run(() => false);
  389. }
  390. }
  391. public virtual bool DeleteList(List<T> entities, bool isCommit = true)
  392. {
  393. if (entities == null || !entities.Any())
  394. {
  395. return false;
  396. }
  397. entities.ToList().ForEach(item =>
  398. {
  399. _context.Set<T>().Attach(item);
  400. _context.Set<T>().Remove(item);
  401. });
  402. if (isCommit)
  403. {
  404. return _unitOfWork.SaveChanges() > 0;
  405. }
  406. else
  407. {
  408. return false;
  409. }
  410. }
  411. public virtual async Task<bool> DeleteListAsync(List<T> entities, bool isCommit = true)
  412. {
  413. if (entities == null || !entities.Any())
  414. {
  415. return await Task.Run(() => false);
  416. }
  417. entities.ToList().ForEach(item =>
  418. {
  419. _context.Set<T>().Attach(item);
  420. _context.Set<T>().Remove(item);
  421. });
  422. if (isCommit)
  423. {
  424. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  425. }
  426. else
  427. {
  428. return await Task.Run(() => false);
  429. }
  430. }
  431. public virtual bool DeleteList<TEntity>(List<TEntity> entities, bool isCommit = true) where TEntity : class
  432. {
  433. if (entities == null || !entities.Any())
  434. {
  435. return false;
  436. }
  437. entities.ToList().ForEach(item =>
  438. {
  439. _context.Set<TEntity>().Attach(item);
  440. _context.Set<TEntity>().Remove(item);
  441. });
  442. if (isCommit)
  443. {
  444. return _unitOfWork.SaveChanges() > 0;
  445. }
  446. else
  447. {
  448. return false;
  449. }
  450. }
  451. public virtual async Task<bool> DeleteListAsync<TEntity>(List<TEntity> entities, bool isCommit = true) where TEntity : class
  452. {
  453. if (entities == null || !entities.Any())
  454. {
  455. return await Task.Run(() => false);
  456. }
  457. entities.ToList().ForEach(item =>
  458. {
  459. _context.Set<TEntity>().Attach(item);
  460. _context.Set<TEntity>().Remove(item);
  461. });
  462. if (isCommit)
  463. {
  464. return await Task.Run(() => _unitOfWork.SaveChanges() > 0);
  465. }
  466. else
  467. {
  468. return await Task.Run(() => false);
  469. }
  470. }
  471. #endregion
  472. #region 获取多条数据操作
  473. public virtual IQueryable<T> LoadAll(Expression<Func<T, bool>> predicate)
  474. {
  475. return predicate != null ? _context.Set<T>().Where(predicate) : _context.Set<T>().AsQueryable<T>();
  476. }
  477. public virtual async Task<IQueryable<T>> LoadAllAsync(Expression<Func<T, bool>> predicate)
  478. {
  479. return predicate != null ? await Task.Run(() => _context.Set<T>().Where(predicate)) : await Task.Run(() => _context.Set<T>().AsQueryable<T>());
  480. }
  481. public virtual List<T> LoadListAll(Expression<Func<T, bool>> predicate)
  482. {
  483. return predicate != null ? _context.Set<T>().Where(predicate).ToList() : _context.Set<T>().AsQueryable<T>().ToList();
  484. }
  485. public virtual async Task<List<T>> LoadListAllAsync(Expression<Func<T, bool>> predicate)
  486. {
  487. return predicate != null ? await Task.Run(() => _context.Set<T>().Where(predicate).ToList()) : await Task.Run(() => _context.Set<T>().AsQueryable<T>().ToList());
  488. }
  489. public virtual IQueryable<T> LoadAllBySql(string sql, params DbParameter[] para)
  490. {
  491. return _context.Set<T>().FromSql(sql, para);
  492. }
  493. public virtual async Task<IQueryable<T>> LoadAllBySqlAsync(string sql, params DbParameter[] para)
  494. {
  495. return await Task.Run(() => _context.Set<T>().FromSql(sql, para));
  496. }
  497. public virtual List<T> LoadListAllBySql(string sql, params DbParameter[] para)
  498. {
  499. return _context.Set<T>().FromSql(sql, para).Cast<T>().ToList();
  500. }
  501. public virtual async Task<List<T>> LoadListAllBySqlAsync(string sql, params DbParameter[] para)
  502. {
  503. return await Task.Run(() => _context.Set<T>().FromSql(sql, para).Cast<T>().ToList());
  504. }
  505. public virtual List<TResult> QueryEntity<TEntity, TOrderBy, TResult>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Expression<Func<TEntity, TResult>> selector, bool isAsc)
  506. where TEntity : class
  507. where TResult : class
  508. {
  509. IQueryable<TEntity> query = _context.Set<TEntity>();
  510. if (where != null)
  511. {
  512. query = query.Where(where);
  513. }
  514. if (orderby != null)
  515. {
  516. query = isAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
  517. }
  518. if (selector == null)
  519. {
  520. return query.Cast<TResult>().ToList();
  521. }
  522. return query.Select(selector).ToList();
  523. }
  524. public virtual async Task<List<TResult>> QueryEntityAsync<TEntity, TOrderBy, TResult>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Expression<Func<TEntity, TResult>> selector, bool isAsc)
  525. where TEntity : class
  526. where TResult : class
  527. {
  528. IQueryable<TEntity> query = _context.Set<TEntity>();
  529. if (where != null)
  530. {
  531. query = query.Where(where);
  532. }
  533. if (orderby != null)
  534. {
  535. query = isAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
  536. }
  537. if (selector == null)
  538. {
  539. return await Task.Run(() => query.Cast<TResult>().ToList());
  540. }
  541. return await Task.Run(() => query.Select(selector).ToList());
  542. }
  543. public virtual List<object> QueryObject<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>, List<object>> selector, bool isAsc) where TEntity : class
  544. {
  545. IQueryable<TEntity> query = _context.Set<TEntity>();
  546. if (where != null)
  547. {
  548. query = query.Where(where);
  549. }
  550. if (orderby != null)
  551. {
  552. query = isAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
  553. }
  554. if (selector == null)
  555. {
  556. return query.ToList<object>();
  557. }
  558. return selector(query);
  559. }
  560. public virtual async Task<List<object>> QueryObjectAsync<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>, List<object>> selector, bool isAsc) where TEntity : class
  561. {
  562. IQueryable<TEntity> query = _context.Set<TEntity>();
  563. if (where != null)
  564. {
  565. query = query.Where(where);
  566. }
  567. if (orderby != null)
  568. {
  569. query = isAsc ? query.OrderBy(orderby) : query.OrderByDescending(orderby);
  570. }
  571. if (selector == null)
  572. {
  573. return await Task.Run(() => query.ToList<object>());
  574. }
  575. return await Task.Run(() => selector(query));
  576. }
  577. public virtual dynamic QueryDynamic<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>, List<object>> selector, bool isAsc) where TEntity : class
  578. {
  579. //List<object> list = QueryObject<TEntity, TOrderBy>
  580. // (where, orderby, selector, isAsc);
  581. //return Common.JsonHelper.JsonConvert.JsonClass(list);
  582. throw new NotImplementedException();
  583. }
  584. public virtual async Task<dynamic> QueryDynamicAsync<TEntity, TOrderBy>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TOrderBy>> orderby, Func<IQueryable<TEntity>, List<object>> selector, bool isAsc) where TEntity : class
  585. {
  586. // List<object> list = QueryObject<TEntity, TOrderBy>
  587. //(where, orderby, selector, isAsc);
  588. // return await Task.Run(() => Common.JsonHelper.JsonConvert.JsonClass(list));
  589. throw new NotImplementedException();
  590. }
  591. #endregion
  592. #region 验证是否存在
  593. public virtual bool IsExist(Expression<Func<T, bool>> predicate)
  594. {
  595. var entry = _context.Set<T>().Where(predicate);
  596. return (entry.Any());
  597. }
  598. public virtual async Task<bool> IsExistAsync(Expression<Func<T, bool>> predicate)
  599. {
  600. var entry = _context.Set<T>().Where(predicate);
  601. return await Task.Run(() => entry.Any());
  602. }
  603. public virtual bool IsExist(string sql, params DbParameter[] para)
  604. {
  605. return _context.Database.ExecuteSqlCommand(sql, para) > 0;
  606. }
  607. public virtual async Task<bool> IsExistAsync(string sql, params DbParameter[] para)
  608. {
  609. return await Task.Run(() => _context.Database.ExecuteSqlCommand(sql, para) > 0);
  610. }
  611. #endregion
  612. public virtual Page<T> PageList(int pageindex, int pagesize, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy, Expression<Func<T, T>> selector, out int total, Expression<Func<T, bool>> where = null)
  613. {
  614. int row = (--pageindex) * pagesize;
  615. if (where != null)
  616. {
  617. total = _context.Set<T>().Where(where).Count();
  618. var data = orderBy(_context.Set<T>().Where(where))
  619. .Skip(row)
  620. .Take(pagesize)
  621. .Select(selector).ToList();
  622. var res = new Page<T>(data, pagesize, total);
  623. return res;
  624. }
  625. else
  626. {
  627. total = _context.Set<T>().Count();
  628. var data = orderBy(_context.Set<T>()).Skip(row)
  629. .Take(pagesize)
  630. .Select(selector).ToList();
  631. var res = new Page<T>(data, pagesize, total);
  632. return res;
  633. }
  634. }
  635. public virtual Page<T> PageList<S>(int pageindex, int pagesize, Expression<Func<T, bool>> predicate, Expression<Func<T, S>> orderPredicate, bool isAsc)
  636. {
  637. var data = _context.Set<T>().AsQueryable();
  638. if (predicate != null)
  639. {
  640. data = data.Where(predicate);
  641. }
  642. var count = data.Count();
  643. if (isAsc)
  644. {
  645. data = data.OrderBy(orderPredicate).Skip((pageindex - 1) * pagesize).Take(pagesize);
  646. return new Page<T>(data.ToList(), pagesize, count);
  647. }
  648. else
  649. {
  650. data = data.OrderByDescending(orderPredicate).Skip((pageindex - 1) * pagesize).Take(pagesize);
  651. return new Page<T>(data.ToList(), pagesize, count);
  652. }
  653. }
  654. }
  655. }