Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

LuEfCrudDataAccess.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using Luticate2.Utils.Dbo.Basic;
  6. using Luticate2.Utils.Dbo.OrderBy;
  7. using Luticate2.Utils.Dbo.Result;
  8. using Luticate2.Utils.Interfaces;
  9. using Luticate2.Utils.Utils;
  10. using Microsoft.EntityFrameworkCore;
  11. namespace Luticate2.Utils.DataAccess
  12. {
  13. public abstract class LuEfCrudDataAccess<TModel, TDboCreate, TDboRead, TDboUpdate, TDbContext> :
  14. LuEfDataAccess<TModel, TDbContext>, ILuCrudInterface<TDboCreate, TDboRead, TDboUpdate>
  15. where TModel : class
  16. where TDboCreate : class
  17. where TDboRead : class
  18. where TDboUpdate : class
  19. where TDbContext : DbContext
  20. {
  21. protected LuEfCrudDataAccess(TDbContext db, DbSet<TModel> table) : base(db, table)
  22. {
  23. }
  24. protected abstract TModel GetModelFromTCreate(TDboCreate obj);
  25. protected abstract void EditModelFromTUpdate(TDboUpdate obj, TModel model);
  26. protected abstract TDboRead GetDboFromModel(TModel model);
  27. protected virtual Expression<Func<TModel, object>> GetOrderByFieldExpression(string fieldName)
  28. {
  29. fieldName = fieldName.ToSnakeCase();
  30. if (!typeof(TModel).HasProperty(fieldName))
  31. {
  32. return null;
  33. }
  34. var param = Expression.Parameter(typeof(TModel), "x");
  35. var prop = Expression.Property(param, fieldName);
  36. var converted = Expression.Convert(prop, typeof(object));
  37. var exp = Expression.Lambda<Func<TModel, object>>(converted, param);
  38. return exp;
  39. }
  40. protected Func<TDboRead, T> GetIdFunc<T>()
  41. {
  42. var param = Expression.Parameter(typeof(TDboRead), "x");
  43. var exp = Expression.Property(param, "Id");
  44. var lambda = Expression.Lambda<Func<TDboRead, T>>(exp, param);
  45. var func = lambda.Compile();
  46. return func;
  47. }
  48. protected TModel GetModelFromTUpdate(TDboUpdate obj, TModel model)
  49. {
  50. EditModelFromTUpdate(obj, model);
  51. return model;
  52. }
  53. protected Guid? GetGuid(string id)
  54. {
  55. Guid guid;
  56. if (Guid.TryParse(id, out guid))
  57. {
  58. return guid;
  59. }
  60. return null;
  61. }
  62. protected LuResult<T> GetNotFoundResult<T>()
  63. {
  64. return LuResult<T>.Error(LuStatus.NotFound, typeof(TModel).Name + ": Value not found", "");
  65. }
  66. public LuResult<T> Add<T>(IEnumerable<TDboCreate> objs, Func<IEnumerable<TDboRead>, T> returnFunc)
  67. {
  68. return Execute(() =>
  69. {
  70. var models = objs.Select(GetModelFromTCreate).ToList();
  71. Table.AddRange(models);
  72. Db.SaveChanges();
  73. var dbos = models.Select(GetDboFromModel).ToList();
  74. var res = returnFunc(dbos);
  75. return LuResult<T>.Ok(res);
  76. });
  77. }
  78. public LuResult<T> Add<T>(TDboCreate obj, Func<TDboRead, T> returnFunc)
  79. {
  80. return Add(new List<TDboCreate> {obj}, list => returnFunc(list.First()));
  81. }
  82. public LuResult<IEnumerable<string>> AddGuid(IEnumerable<TDboCreate> objs)
  83. {
  84. var func = GetIdFunc<string>();
  85. return Add(objs, list => list.Select(func));
  86. }
  87. public LuResult<string> AddGuid(TDboCreate obj)
  88. {
  89. return AddGuid(new List<TDboCreate> {obj}).To(list => list.First());
  90. }
  91. public LuResult<IEnumerable<long>> AddId(IEnumerable<TDboCreate> obj)
  92. {
  93. var func = GetIdFunc<long>();
  94. return Add(obj, list => list.Select(func));
  95. }
  96. public LuResult<long> AddId(TDboCreate obj)
  97. {
  98. return AddId(new List<TDboCreate> {obj}).To(list => list.First());
  99. }
  100. public LuResult<IEnumerable<TDboRead>> AddDbo(IEnumerable<TDboCreate> obj)
  101. {
  102. return Add(obj, read => read);
  103. }
  104. public LuResult<TDboRead> AddDbo(TDboCreate obj)
  105. {
  106. return AddDbo(new List<TDboCreate> {obj}).To(list => list.First());
  107. }
  108. public LuResult<TDboRead> GetSingle(Expression<Func<TModel, bool>> predicate)
  109. {
  110. return Execute(() =>
  111. {
  112. var model = Table.FirstOrDefault(predicate);
  113. if (model == default(TModel))
  114. {
  115. return GetNotFoundResult<TDboRead>();
  116. }
  117. var dbo = GetDboFromModel(model);
  118. return LuResult<TDboRead>.Ok(dbo);
  119. });
  120. }
  121. public LuResult<TDboRead> GetSingleByKeys(params KeyValuePair<string, object>[] keys)
  122. {
  123. return GetSingle(GetExpression(keys));
  124. }
  125. public LuResult<TDboRead> GetSingleById(string id)
  126. {
  127. var guid = GetGuid(id);
  128. if (guid == null)
  129. {
  130. return GetNotFoundResult<TDboRead>();
  131. }
  132. return GetSingleByKeys(new KeyValuePair<string, object>("id", guid));
  133. }
  134. public LuResult<TDboRead> GetSingleById(long id)
  135. {
  136. return GetSingleByKeys(new KeyValuePair<string, object>("id", id));
  137. }
  138. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Func<DbSet<TModel>, IOrderedQueryable<TModel>> orderBy,
  139. Expression<Func<TModel, bool>> predicate, int page = 0, int perPage = int.MaxValue,
  140. params Func<IOrderedQueryable<TModel>, IOrderedQueryable<TModel>>[] otherOrderBy)
  141. {
  142. return Execute(() =>
  143. {
  144. var count = Table.Count(predicate);
  145. var ordered = orderBy(Table);
  146. foreach (var func in otherOrderBy)
  147. {
  148. ordered = func(ordered);
  149. }
  150. var data = ordered.Where(predicate).Skip(page * perPage).Take(perPage).Select(GetDboFromModel).ToList();
  151. var result = new LuPaginatedDbo<TDboRead>
  152. {
  153. Count = count,
  154. Data = data
  155. };
  156. return LuResult<LuPaginatedDbo<TDboRead>>.Ok(result);
  157. });
  158. }
  159. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Expression<Func<TModel, object>> orderBy,
  160. Expression<Func<TModel, bool>> predicate, int page = 0, int perPage = int.MaxValue,
  161. params Expression<Func<TModel, object>>[] otherOrderBy)
  162. {
  163. return GetMultiple(table => table.OrderBy(orderBy), predicate, page, perPage,
  164. otherOrderBy.Select<Expression<Func<TModel, object>>, Func<IOrderedQueryable<TModel>,
  165. IOrderedQueryable<TModel>>>(expression => (t => t.ThenBy(expression))).ToArray());
  166. }
  167. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Func<DbSet<TModel>, IOrderedQueryable<TModel>> orderBy,
  168. int page = 0, int perPage = int.MaxValue, params Func<IOrderedQueryable<TModel>, IOrderedQueryable<TModel>>[] otherOrderBy)
  169. {
  170. return GetMultiple(orderBy, x => true, page, perPage, otherOrderBy);
  171. }
  172. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Expression<Func<TModel, object>> orderBy,
  173. int page = 0, int perPage = int.MaxValue, params Expression<Func<TModel, object>>[] otherOrderBy)
  174. {
  175. return GetMultiple(orderBy, x => true, page, perPage, otherOrderBy);
  176. }
  177. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(LuOrderByDbo orderBy, int page = 0, int perPage = int.MaxValue)
  178. {
  179. return Execute(() =>
  180. {
  181. var count = Table.Count();
  182. IOrderedQueryable<TModel> ordered = null;
  183. foreach (var field in orderBy.Fields)
  184. {
  185. var exp = GetOrderByFieldExpression(field.Name);
  186. if (exp == null)
  187. {
  188. return LuResult<LuPaginatedDbo<TDboRead>>.Error(LuStatus.InputError,
  189. string.Format("LuEfCrudDataAccess: {0}", field.Name), "Invalid order by field");
  190. }
  191. if (ordered != null)
  192. {
  193. ordered = field.Asc ? ordered.ThenBy(exp) : ordered.ThenByDescending(exp);
  194. }
  195. else
  196. {
  197. ordered = field.Asc ? Table.OrderBy(exp) : Table.OrderByDescending(exp);
  198. }
  199. }
  200. var data = ordered.Skip(page * perPage).Take(perPage).Select(GetDboFromModel).ToList();
  201. var result = new LuPaginatedDbo<TDboRead>
  202. {
  203. Count = count,
  204. Data = data
  205. };
  206. return LuResult<LuPaginatedDbo<TDboRead>>.Ok(result);
  207. });
  208. }
  209. public LuResult<T> Edit<T>(Expression<Func<TModel, bool>> predicate, Action<TModel> update,
  210. Func<IEnumerable<TDboRead>, T> returnFunc)
  211. {
  212. return Execute(() =>
  213. {
  214. var models = Table.Where(predicate);
  215. var editedDbos = new List<TDboRead>();
  216. foreach (var model in models)
  217. {
  218. update(model);
  219. editedDbos.Add(GetDboFromModel(model));
  220. Db.Entry(model).State = EntityState.Modified;
  221. }
  222. Db.SaveChanges();
  223. var res = returnFunc(editedDbos);
  224. return LuResult<T>.Ok(res);
  225. });
  226. }
  227. public LuResult<IEnumerable<string>> EditGuid(Expression<Func<TModel, bool>> predicate, Action<TModel> update)
  228. {
  229. var func = GetIdFunc<string>();
  230. return Edit(predicate, update, reads => reads.Select(func));
  231. }
  232. public LuResult<IEnumerable<long>> EditId(Expression<Func<TModel, bool>> predicate, Action<TModel> update)
  233. {
  234. var func = GetIdFunc<long>();
  235. return Edit(predicate, update, reads => reads.Select(func));
  236. }
  237. public LuResult<IEnumerable<TDboRead>> EditDbo(Expression<Func<TModel, bool>> predicate, Action<TModel> update)
  238. {
  239. return Edit(predicate, update, read => read);
  240. }
  241. public LuResult<T> EditSingleById<T>(long id, Action<TModel> update, Func<TDboRead, T> returnFunc)
  242. {
  243. return Edit(GetExpression(new KeyValuePair<string, object>("id", id)), update,
  244. list => returnFunc(list.FirstOrDefault()));
  245. }
  246. public LuResult<long> EditSingleByIdId(long id, Action<TModel> update)
  247. {
  248. var func = GetIdFunc<long>();
  249. return EditSingleById(id, update, func);
  250. }
  251. public LuResult<TDboRead> EditSingleByIdDbo(long id, Action<TModel> update)
  252. {
  253. return EditSingleById(id, update, read => read);
  254. }
  255. public LuResult<T> EditSingleById<T>(string id, Action<TModel> update, Func<TDboRead, T> returnFunc)
  256. {
  257. var guid = GetGuid(id);
  258. if (guid == null)
  259. {
  260. return GetNotFoundResult<T>();
  261. }
  262. return Edit(GetExpression(new KeyValuePair<string, object>("id", guid)), update,
  263. list => returnFunc(list.FirstOrDefault()));
  264. }
  265. public LuResult<string> EditSingleByIdGuid(string id, Action<TModel> update)
  266. {
  267. return EditSingleById(id, update, GetIdFunc<string>());
  268. }
  269. public LuResult<TDboRead> EditSingleByIdDbo(string id, Action<TModel> update)
  270. {
  271. return EditSingleById(id, update, read => read);
  272. }
  273. public LuResult<T> EditSingleById<T>(long id, TDboUpdate update, Func<TDboRead, T> returnFunc)
  274. {
  275. return Edit(GetExpression(new KeyValuePair<string, object>("id", id)),
  276. model => EditModelFromTUpdate(update, model), list => returnFunc(list.FirstOrDefault()));
  277. }
  278. public LuResult<long> EditSingleByIdId(long id, TDboUpdate update)
  279. {
  280. return EditSingleById(id, update, GetIdFunc<long>());
  281. }
  282. public LuResult<TDboRead> EditSingleByIdDbo(long id, TDboUpdate update)
  283. {
  284. return EditSingleById(id, update, read => read);
  285. }
  286. public LuResult<T> EditSingleById<T>(string id, TDboUpdate update, Func<TDboRead, T> returnFunc)
  287. {
  288. var guid = GetGuid(id);
  289. if (guid == null)
  290. {
  291. return GetNotFoundResult<T>();
  292. }
  293. return Edit(GetExpression(new KeyValuePair<string, object>("id", guid)),
  294. model => EditModelFromTUpdate(update, model), list => returnFunc(list.FirstOrDefault()));
  295. }
  296. public LuResult<string> EditSingleByIdGuid(string id, TDboUpdate update)
  297. {
  298. return EditSingleById(id, update, GetIdFunc<string>());
  299. }
  300. public LuResult<TDboRead> EditSingleByIdDbo(string id, TDboUpdate update)
  301. {
  302. return EditSingleById(id, update, read => read);
  303. }
  304. public LuResult<T> Delete<T>(Expression<Func<TModel, bool>> predicate,
  305. Func<IEnumerable<TDboRead>, T> returnFunc)
  306. {
  307. return Execute(() =>
  308. {
  309. var models = Table.Where(predicate).ToList();
  310. Table.RemoveRange(models);
  311. Db.SaveChanges();
  312. var dbos = models.Select(GetDboFromModel);
  313. return LuResult<T>.Ok(returnFunc(dbos));
  314. });
  315. }
  316. public LuResult<IEnumerable<string>> DeleteGuid(Expression<Func<TModel, bool>> predicate)
  317. {
  318. var func = GetIdFunc<string>();
  319. return Delete(predicate, reads => reads.Select(func));
  320. }
  321. public LuResult<IEnumerable<long>> DeleteId(Expression<Func<TModel, bool>> predicate)
  322. {
  323. var func = GetIdFunc<long>();
  324. return Delete(predicate, reads => reads.Select(func));
  325. }
  326. public LuResult<IEnumerable<TDboRead>> DeleteDbo(Expression<Func<TModel, bool>> predicate)
  327. {
  328. return Delete(predicate, read => read);
  329. }
  330. public LuResult<T> DeleteSingleById<T>(string id, Func<TDboRead, T> returnFunc)
  331. {
  332. var guid = GetGuid(id);
  333. if (guid == null)
  334. {
  335. return GetNotFoundResult<T>();
  336. }
  337. return Delete(GetExpression(new KeyValuePair<string, object>("id", guid)),
  338. reads => returnFunc(reads.FirstOrDefault()));
  339. }
  340. public LuResult<string> DeleteSingleByIdGuid(string id)
  341. {
  342. var func = GetIdFunc<string>();
  343. return DeleteSingleById(id, func);
  344. }
  345. public LuResult<TDboRead> DeleteSingleByIdDbo(string id)
  346. {
  347. return DeleteSingleById(id, read => read);
  348. }
  349. public LuResult<T> DeleteSingleById<T>(long id, Func<TDboRead, T> returnFunc)
  350. {
  351. return Delete(GetExpression(new KeyValuePair<string, object>("id", id)),
  352. reads => returnFunc(reads.First()));
  353. }
  354. public LuResult<long> DeleteSingleByIdId(long id)
  355. {
  356. var func = GetIdFunc<long>();
  357. return DeleteSingleById(id, func);
  358. }
  359. public LuResult<TDboRead> DeleteSingleByIdDbo(long id)
  360. {
  361. return DeleteSingleById(id, read => read);
  362. }
  363. }
  364. }