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 16KB

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