LogRepository.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Microsoft.EntityFrameworkCore;
  11. namespace Repository
  12. {
  13. public class LogRepository : IRepository
  14. {
  15. public DbContext GetCurrentDbContext()
  16. {
  17. var context = new LogDbContext();
  18. return context;
  19. }
  20. public bool Add<T>(T entity) where T : class
  21. {
  22. using var context = GetCurrentDbContext();
  23. context.Set<T>().Add(entity);
  24. var count = context.SaveChanges();
  25. return count > 0;
  26. }
  27. public async Task<bool> AddAsync<T>(T entity) where T : class
  28. {
  29. await using var context = GetCurrentDbContext();
  30. await context.Set<T>().AddAsync(entity);
  31. var count = await context.SaveChangesAsync();
  32. return count > 0;
  33. }
  34. public bool AddRange<T>(IEnumerable<T> entity) where T : class
  35. {
  36. using var context = GetCurrentDbContext();
  37. context.Set<T>().AddRange(entity);
  38. var count = context.SaveChanges();
  39. return count > 0;
  40. }
  41. public async Task<bool> AddRangeAsync<T>(IEnumerable<T> entity) where T : class
  42. {
  43. await using var context = GetCurrentDbContext();
  44. await context.Set<T>().AddRangeAsync(entity);
  45. var count = await context.SaveChangesAsync();
  46. return count > 0;
  47. }
  48. public bool Delete<T>(T entity) where T : class
  49. {
  50. using var context = GetCurrentDbContext();
  51. context.Set<T>().Attach(entity);
  52. context.Set<T>().Remove(entity);
  53. var count = context.SaveChanges();
  54. return count > 0;
  55. }
  56. public bool DeleteAll<T>() where T : class
  57. {
  58. using var context = GetCurrentDbContext();
  59. var entities = context.Set<T>().ToArray();
  60. if (entities.Length == 0)
  61. {
  62. return false;
  63. }
  64. context.Set<T>().RemoveRange(entities);
  65. var count = context.SaveChanges();
  66. return true;
  67. }
  68. public async Task<bool> DeleteAllAsync<T>() where T : class
  69. {
  70. await using var context = GetCurrentDbContext();
  71. var entities = await context.Set<T>().ToArrayAsync();
  72. if (entities.Length == 0)
  73. {
  74. return false;
  75. }
  76. context.Set<T>().RemoveRange(entities);
  77. var count = context.SaveChanges();
  78. return true;
  79. }
  80. public bool Delete<T>(Expression<Func<T, bool>> whereLambda) where T : class
  81. {
  82. using var context = GetCurrentDbContext();
  83. var entityModel = context.Set<T>().Where(whereLambda).FirstOrDefault();
  84. if (entityModel == null) return false;
  85. context.Set<T>().Remove(entityModel);
  86. var count = context.SaveChanges();
  87. return count > 0;
  88. }
  89. public async Task<bool> DeleteAsync<T>(Expression<Func<T, bool>> whereLambda) where T : class
  90. {
  91. await using var context = GetCurrentDbContext();
  92. var entityModel = await context.Set<T>().Where(whereLambda).FirstOrDefaultAsync();
  93. if (entityModel == null) return false;
  94. context.Set<T>().Remove(entityModel);
  95. var count = await context.SaveChangesAsync();
  96. return count > 0;
  97. }
  98. public bool DeleteById<T>(dynamic id) where T : class
  99. {
  100. using var context = GetCurrentDbContext();
  101. var entityModel = context.Set<T>().Find(id);
  102. if (entityModel == null) return false;
  103. context.Set<T>().Remove(entityModel);
  104. var count = context.SaveChanges();
  105. return count > 0;
  106. }
  107. public async Task<bool> DeleteByIdAsync<T>(dynamic id) where T : class
  108. {
  109. await using var context = GetCurrentDbContext();
  110. var entityModel = await context.Set<T>().FindAsync(id);
  111. if (entityModel == null) return false;
  112. context.Set<T>().Remove(entityModel);
  113. var count = await context.SaveChangesAsync();
  114. return count > 0;
  115. }
  116. public bool Update<T>(T entity) where T : class
  117. {
  118. using var context = GetCurrentDbContext();
  119. var entityModel = context.Entry(entity);
  120. context.Set<T>().Attach(entity);
  121. entityModel.State = EntityState.Modified;
  122. var count = context.SaveChanges();
  123. return count > 0;
  124. }
  125. public async Task<bool> UpdateAsync<T>(T entity) where T : class
  126. {
  127. await using var context = GetCurrentDbContext();
  128. var entityModel = context.Entry(entity);
  129. context.Set<T>().Attach(entity);
  130. entityModel.State = EntityState.Modified;
  131. var count = await context.SaveChangesAsync();
  132. return count > 0;
  133. }
  134. public bool Update<T>(List<T> entities) where T : class
  135. {
  136. using var context = GetCurrentDbContext();
  137. if (entities != null)
  138. {
  139. foreach (var item in entities)
  140. {
  141. var entityModel = context.Entry(entities);
  142. context.Set<T>().Attach(item);
  143. entityModel.State = EntityState.Modified;
  144. }
  145. }
  146. var count = context.SaveChanges();
  147. return count > 0;
  148. }
  149. //查询要修改的数据
  150. public bool Update<T>(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames) where T : class
  151. {
  152. using var context = GetCurrentDbContext();
  153. var listModifying = context.Set<T>().Where(whereLambda).ToList();
  154. var t = typeof(T);
  155. var proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
  156. var ditProList = new Dictionary<string, PropertyInfo>();
  157. proInfos.ForEach(p =>
  158. {
  159. if (modifiedProNames.Contains(p.Name))
  160. {
  161. ditProList.Add(p.Name, p);
  162. }
  163. });
  164. if (ditProList.Count <= 0)
  165. {
  166. throw new Exception("指定修改的字段名称有误或为空");
  167. }
  168. foreach (var item in ditProList)
  169. {
  170. var proInfo = item.Value;
  171. var newValue = proInfo.GetValue(model, null);
  172. //批量进行修改相互对应的属性
  173. foreach (var oModel in listModifying)
  174. {
  175. proInfo.SetValue(oModel, newValue, null);//设置其中新的值
  176. }
  177. }
  178. return context.SaveChanges() > 0;
  179. }
  180. public T FindById<T>(dynamic id) where T : class
  181. {
  182. using var context = GetCurrentDbContext();
  183. return context.Set<T>().Find(id);
  184. }
  185. public async Task<T> FindByIdAsync<T>(dynamic id) where T : class
  186. {
  187. await using var context = GetCurrentDbContext();
  188. return await context.Set<T>().FindAsync(id);
  189. }
  190. public T GetFirstDefault<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  191. {
  192. using var context = GetCurrentDbContext();
  193. return whereLambda != null
  194. ? context.Set<T>().Where(whereLambda).FirstOrDefault()
  195. : context.Set<T>().FirstOrDefault();
  196. }
  197. public async Task<T> GetFirstDefaultAsync<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  198. {
  199. await using var context = GetCurrentDbContext();
  200. return whereLambda != null
  201. ? await context.Set<T>().Where(whereLambda).FirstOrDefaultAsync()
  202. : await context.Set<T>().FirstOrDefaultAsync();
  203. }
  204. public List<T> GetAll<T>(string orderProperty = null) where T : class
  205. {
  206. using var context = GetCurrentDbContext();
  207. if (orderProperty == null)
  208. {
  209. return context.Set<T>().ToList();
  210. }
  211. var properties = typeof(T).GetProperties().Select(c => c.Name);
  212. if (!properties.Contains(orderProperty))
  213. {
  214. throw new Exception("Not Find Property Exception");
  215. }
  216. return context.Set<T>().OrderBy(c => c.GetType().GetProperties().First(p => p.Name == orderProperty))
  217. .ToList();
  218. }
  219. public async Task<List<T>> GetAllAsync<T>(string orderProperty = null) where T : class
  220. {
  221. await using var context = GetCurrentDbContext();
  222. if (orderProperty == null)
  223. {
  224. return await context.Set<T>().ToListAsync();
  225. }
  226. var properties = typeof(T).GetProperties().Select(c => c.Name);
  227. if (!properties.Contains(orderProperty))
  228. {
  229. throw new Exception("Not Find Property Exception");
  230. }
  231. return await context.Set<T>().OrderBy(c => c.GetType().GetProperties().First(p => p.Name == orderProperty))
  232. .ToListAsync();
  233. }
  234. public List<T> GetAllQuery<T>(string path, Expression<Func<T, bool>> whereLambda = null) where T : class
  235. {
  236. using var context = GetCurrentDbContext();
  237. return whereLambda != null ? context.Set<T>().Where(whereLambda).Include(path).ToList() : context.Set<T>().Include(path).ToList();
  238. }
  239. public List<T> GetAllQuery<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  240. {
  241. using var context = GetCurrentDbContext();
  242. return whereLambda != null ? context.Set<T>().Where(whereLambda).ToList() : context.Set<T>().ToList();
  243. }
  244. public async Task<List<T>> GetAllQueryAsync<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  245. {
  246. await using var context = GetCurrentDbContext();
  247. return await (whereLambda != null
  248. ? context.Set<T>().Where(whereLambda).ToListAsync()
  249. : context.Set<T>().ToListAsync());
  250. }
  251. public int GetCount<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  252. {
  253. using var context = GetCurrentDbContext();
  254. return whereLambda != null
  255. ? context.Set<T>().Where(whereLambda).Count()
  256. : context.Set<T>().Count();
  257. }
  258. public async Task<int> GetCountAsync<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  259. {
  260. await using var context = GetCurrentDbContext();
  261. return await (whereLambda != null
  262. ? context.Set<T>().Where(whereLambda).CountAsync()
  263. : context.Set<T>().CountAsync());
  264. }
  265. public bool GetAny<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  266. {
  267. using var context = GetCurrentDbContext();
  268. return whereLambda != null ? context.Set<T>().Where(whereLambda).Any() : context.Set<T>().Any();
  269. }
  270. public async Task<bool> GetAnyAsync<T>(Expression<Func<T, bool>> whereLambda = null) where T : class
  271. {
  272. await using var context = GetCurrentDbContext();
  273. return await (whereLambda != null
  274. ? context.Set<T>().Where(whereLambda).AnyAsync()
  275. : context.Set<T>().AnyAsync());
  276. }
  277. public List<T> Pagination<T, TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy,
  278. Expression<Func<T, bool>> whereLambda = null, bool isOrder = true) where T : class
  279. {
  280. using var context = GetCurrentDbContext();
  281. IQueryable<T> queryList =
  282. isOrder ? context.Set<T>().OrderBy(orderBy) : context.Set<T>().OrderByDescending(orderBy);
  283. if (whereLambda != null)
  284. {
  285. queryList = queryList.Where(whereLambda);
  286. }
  287. return queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
  288. }
  289. public async Task<List<T>> PaginationAsync<T, TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy,
  290. Expression<Func<T, bool>> whereLambda = null, bool isOrder = true) where T : class
  291. {
  292. await using var context = GetCurrentDbContext();
  293. IQueryable<T> queryList =
  294. isOrder ? context.Set<T>().OrderBy(orderBy) : context.Set<T>().OrderByDescending(orderBy);
  295. if (whereLambda != null)
  296. {
  297. queryList = queryList.Where(whereLambda);
  298. }
  299. return await queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToListAsync();
  300. }
  301. public List<T> Pagination<T>(int pageIndex, int pageSize, string ordering, Expression<Func<T, bool>> whereLambda = null) where T : class
  302. {
  303. var ditProList = new Dictionary<string, PropertyInfo>();
  304. using var context = GetCurrentDbContext();
  305. var t = typeof(T);
  306. var proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
  307. proInfos.ForEach(p => { ditProList.Add(p.Name, p); });
  308. //分页的时候一定要注意 Order 一定在Skip 之前
  309. var queryList = context.Set<T>()
  310. .OrderBy(c => c.GetType().GetProperties().First(p => p.Name == ordering).Name);
  311. if (whereLambda != null)
  312. {
  313. queryList = (IOrderedQueryable<T>)queryList.Where(whereLambda);
  314. }
  315. return queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
  316. }
  317. public async Task<List<T>> PaginationAsync<T>(int pageIndex, int pageSize, string ordering, Expression<Func<T, bool>> whereLambda = null) where T : class
  318. {
  319. await using var context = GetCurrentDbContext();
  320. var t = typeof(T);
  321. var proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
  322. var ditProList = new Dictionary<string, PropertyInfo>();
  323. proInfos.ForEach(p => { ditProList.Add(p.Name, p); });
  324. //分页的时候一定要注意 Order 一定在Skip 之前
  325. var queryList = context.Set<T>()
  326. .OrderBy(c => c.GetType().GetProperties().First(p => p.Name == ordering).Name);
  327. if (whereLambda != null)
  328. {
  329. queryList = (IOrderedQueryable<T>)queryList.Where(whereLambda);
  330. }
  331. return await queryList.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToListAsync();
  332. }
  333. public List<T> GetSelect<T>(Expression<Func<T, bool>> whereLambda) where T : class
  334. {
  335. using var context = GetCurrentDbContext();
  336. return context.Set<T>().Where(whereLambda).ToList();
  337. }
  338. public List<T> QueryPro<T>(string sql, List<SqlParameter> parameters, CommandType cmdType = CommandType.Text) where T : class
  339. {
  340. using var context = GetCurrentDbContext();
  341. if (parameters == null)
  342. {
  343. throw new ArgumentNullException(nameof(parameters));
  344. }
  345. var array = parameters.ToArray();
  346. var sqlParams = array.Select(item => item).Cast<object>().ToList();
  347. //进行执行存储过程
  348. if (cmdType != CommandType.StoredProcedure)
  349. return context.Set<T>().FromSqlRaw(sql, sqlParams).ToList();
  350. var paraNames = new StringBuilder();
  351. foreach (var item in parameters)
  352. {
  353. paraNames.Append($" @{item},");
  354. }
  355. sql = paraNames.Length > 0 ? $"exec {sql} {paraNames.ToString().Trim(',')}" : $"exec {sql} ";
  356. return context.Set<T>().FromSqlRaw(sql, sqlParams).ToList();
  357. }
  358. public void RollBackChanges<T>() where T : class
  359. {
  360. using var context = GetCurrentDbContext();
  361. var query = context.ChangeTracker.Entries().ToList();
  362. query.ForEach(p => p.State = EntityState.Unchanged);
  363. }
  364. public bool Update<T>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, T>> updateLambda) where T : class
  365. {
  366. throw new NotImplementedException();
  367. }
  368. public Task<bool> UpdateAsync<T>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, T>> updateLambda) where T : class
  369. {
  370. throw new NotImplementedException();
  371. }
  372. }
  373. }