You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuEfCrudDataAccess.cs 17KB

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