Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

LuEfCrudDataAccess.cs 16KB

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