Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

LuEfCrudDataAccess.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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(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 virtual object GetId(TId id)
  56. {
  57. var s = id as string;
  58. if (s != null)
  59. {
  60. Guid guid;
  61. if (Guid.TryParse(s, out guid))
  62. {
  63. return guid;
  64. }
  65. return null;
  66. }
  67. return id;
  68. }
  69. protected LuResult<T> GetNotFoundResult<T>()
  70. {
  71. return LuResult<T>.Error(LuStatus.NotFound, typeof(TModel).Name + ": Value not found", "");
  72. }
  73. protected IQueryable<TModel> GetFilterQuery(LuFilterDbo filter)
  74. {
  75. return Table.Where(GetFilterExpression(filter));
  76. }
  77. public LuResult<T> Add<T>(IEnumerable<TDboCreate> objs, Func<IEnumerable<TDboRead>, T> returnFunc)
  78. {
  79. return Execute(() =>
  80. {
  81. var models = objs.Select(GetModelFromTCreate).ToList();
  82. Table.AddRange(models);
  83. Db.SaveChanges();
  84. var dbos = models.Select(GetDboFromModel).ToList();
  85. var res = returnFunc(dbos);
  86. return LuResult<T>.Ok(res);
  87. });
  88. }
  89. public LuResult<T> Add<T>(TDboCreate obj, Func<TDboRead, T> returnFunc)
  90. {
  91. return Add(new List<TDboCreate> {obj}, list => returnFunc(list.First()));
  92. }
  93. public LuResult<IEnumerable<TId>> AddId(IEnumerable<TDboCreate> objs)
  94. {
  95. var func = GetIdFunc<TId>();
  96. return Add(objs, list => list.Select(func));
  97. }
  98. public LuResult<TId> AddId(TDboCreate obj)
  99. {
  100. return AddId(new List<TDboCreate> {obj}).To(list => list.First());
  101. }
  102. public LuResult<IEnumerable<TDboRead>> AddDbo(IEnumerable<TDboCreate> obj)
  103. {
  104. return Add(obj, read => read);
  105. }
  106. public LuResult<TDboRead> AddDbo(TDboCreate obj)
  107. {
  108. return AddDbo(new List<TDboCreate> {obj}).To(list => list.First());
  109. }
  110. public LuResult<TDboRead> GetSingle(Expression<Func<TModel, bool>> predicate)
  111. {
  112. return Execute(() =>
  113. {
  114. var model = Table.FirstOrDefault(predicate);
  115. if (model == default(TModel))
  116. {
  117. return GetNotFoundResult<TDboRead>();
  118. }
  119. var dbo = GetDboFromModel(model);
  120. return LuResult<TDboRead>.Ok(dbo);
  121. });
  122. }
  123. public LuResult<TDboRead> GetSingleByKeys(params KeyValuePair<string, object>[] keys)
  124. {
  125. return GetSingle(GetExpression(keys));
  126. }
  127. public LuResult<TDboRead> GetSingleById(TId id)
  128. {
  129. var guid = GetId(id);
  130. if (guid == null)
  131. {
  132. return GetNotFoundResult<TDboRead>();
  133. }
  134. return GetSingleByKeys(new KeyValuePair<string, object>("id", guid));
  135. }
  136. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Func<DbSet<TModel>, IOrderedQueryable<TModel>> orderBy,
  137. Expression<Func<TModel, bool>> predicate, int page = 0, int perPage = int.MaxValue,
  138. params Func<IOrderedQueryable<TModel>, IOrderedQueryable<TModel>>[] otherOrderBy)
  139. {
  140. return Execute(() =>
  141. {
  142. var count = Table.Count(predicate);
  143. var ordered = orderBy(Table);
  144. foreach (var func in otherOrderBy)
  145. {
  146. ordered = func(ordered);
  147. }
  148. var data = ordered.Where(predicate).Skip(page * perPage).Take(perPage).Select(GetDboFromModel).ToList();
  149. var result = new LuPaginatedDbo<TDboRead>
  150. {
  151. Count = count,
  152. Data = data
  153. };
  154. return LuResult<LuPaginatedDbo<TDboRead>>.Ok(result);
  155. });
  156. }
  157. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Expression<Func<TModel, object>> orderBy,
  158. Expression<Func<TModel, bool>> predicate, int page = 0, int perPage = int.MaxValue,
  159. params Expression<Func<TModel, object>>[] otherOrderBy)
  160. {
  161. return GetMultiple(table => table.OrderBy(orderBy), predicate, page, perPage,
  162. otherOrderBy.Select<Expression<Func<TModel, object>>, Func<IOrderedQueryable<TModel>,
  163. IOrderedQueryable<TModel>>>(expression => (t => t.ThenBy(expression))).ToArray());
  164. }
  165. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Func<DbSet<TModel>, IOrderedQueryable<TModel>> orderBy,
  166. int page = 0, int perPage = int.MaxValue, params Func<IOrderedQueryable<TModel>, IOrderedQueryable<TModel>>[] otherOrderBy)
  167. {
  168. return GetMultiple(orderBy, x => true, page, perPage, otherOrderBy);
  169. }
  170. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(Expression<Func<TModel, object>> orderBy,
  171. int page = 0, int perPage = int.MaxValue, params Expression<Func<TModel, object>>[] otherOrderBy)
  172. {
  173. return GetMultiple(orderBy, x => true, page, perPage, otherOrderBy);
  174. }
  175. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(LuOrderByDbo orderBy, IQueryable<TModel> queryable,
  176. int page = 0, int perPage = int.MaxValue)
  177. {
  178. return Execute(() =>
  179. {
  180. var count = queryable.Count();
  181. IOrderedQueryable<TModel> ordered = null;
  182. foreach (var field in orderBy.Fields)
  183. {
  184. var exp = GetOrderByFieldExpression(field.Name);
  185. if (exp == null)
  186. {
  187. return LuResult<LuPaginatedDbo<TDboRead>>.Error(LuStatus.InputError,
  188. string.Format("LuEfCrudDataAccess: {0}", field.Name), "Invalid order by field");
  189. }
  190. if (ordered != null)
  191. {
  192. ordered = field.Asc ? ordered.ThenBy(exp) : ordered.ThenByDescending(exp);
  193. }
  194. else
  195. {
  196. ordered = field.Asc ? queryable.OrderBy(exp) : queryable.OrderByDescending(exp);
  197. }
  198. }
  199. var data = ordered.Skip(page * perPage).Take(perPage).Select(GetDboFromModel).ToList();
  200. var result = new LuPaginatedDbo<TDboRead>
  201. {
  202. Count = count,
  203. Data = data
  204. };
  205. return LuResult<LuPaginatedDbo<TDboRead>>.Ok(result);
  206. });
  207. }
  208. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(LuOrderByDbo orderBy, LuFilterDbo filter,
  209. int page = 0, int perPage = int.MaxValue)
  210. {
  211. return GetMultiple(orderBy, GetFilterQuery(filter), page, perPage);
  212. }
  213. public LuResult<LuPaginatedDbo<TDboRead>> GetMultiple(LuOrderByDbo orderBy, int page = 0, int perPage = int.MaxValue)
  214. {
  215. return GetMultiple(orderBy, Table, page, perPage);
  216. }
  217. public LuResult<T> Edit<T>(Expression<Func<TModel, bool>> predicate, Action<TModel> update,
  218. Func<IEnumerable<TDboRead>, T> returnFunc)
  219. {
  220. return Execute(() =>
  221. {
  222. var models = Table.Where(predicate);
  223. var editedDbos = new List<TDboRead>();
  224. foreach (var model in models)
  225. {
  226. update(model);
  227. editedDbos.Add(GetDboFromModel(model));
  228. Db.Entry(model).State = EntityState.Modified;
  229. }
  230. Db.SaveChanges();
  231. var res = returnFunc(editedDbos);
  232. return LuResult<T>.Ok(res);
  233. });
  234. }
  235. public LuResult<IEnumerable<TId>> EditId(Expression<Func<TModel, bool>> predicate, Action<TModel> update)
  236. {
  237. var func = GetIdFunc<TId>();
  238. return Edit(predicate, update, reads => reads.Select(func));
  239. }
  240. public LuResult<IEnumerable<TDboRead>> EditDbo(Expression<Func<TModel, bool>> predicate, Action<TModel> update)
  241. {
  242. return Edit(predicate, update, read => read);
  243. }
  244. public LuResult<T> EditSingleById<T>(TId id, Action<TModel> update, Func<TDboRead, T> returnFunc)
  245. {
  246. var guid = GetId(id);
  247. if (guid == null)
  248. {
  249. return GetNotFoundResult<T>();
  250. }
  251. return Edit(GetExpression(new KeyValuePair<string, object>("id", guid)), update,
  252. list => returnFunc(list.FirstOrDefault()));
  253. }
  254. public LuResult<TId> EditSingleByIdId(TId id, Action<TModel> update)
  255. {
  256. return EditSingleById(id, update, GetIdFunc<TId>());
  257. }
  258. public LuResult<TDboRead> EditSingleByIdDbo(TId id, Action<TModel> update)
  259. {
  260. return EditSingleById(id, update, read => read);
  261. }
  262. public LuResult<T> EditSingleById<T>(TId id, TDboUpdate update, Func<TDboRead, T> returnFunc)
  263. {
  264. var guid = GetId(id);
  265. if (guid == null)
  266. {
  267. return GetNotFoundResult<T>();
  268. }
  269. return Edit(GetExpression(new KeyValuePair<string, object>("id", guid)),
  270. model => EditModelFromTUpdate(update, model), list => returnFunc(list.FirstOrDefault()));
  271. }
  272. public LuResult<TId> EditSingleByIdId(TId id, TDboUpdate update)
  273. {
  274. return EditSingleById(id, update, GetIdFunc<TId>());
  275. }
  276. public LuResult<TDboRead> EditSingleByIdDbo(TId id, TDboUpdate update)
  277. {
  278. return EditSingleById(id, update, read => read);
  279. }
  280. public LuResult<T> Delete<T>(Expression<Func<TModel, bool>> predicate,
  281. Func<IEnumerable<TDboRead>, T> returnFunc)
  282. {
  283. return Execute(() =>
  284. {
  285. var models = Table.Where(predicate).ToList();
  286. Table.RemoveRange(models);
  287. Db.SaveChanges();
  288. var dbos = models.Select(GetDboFromModel);
  289. return LuResult<T>.Ok(returnFunc(dbos));
  290. });
  291. }
  292. public LuResult<IEnumerable<TId>> DeleteId(Expression<Func<TModel, bool>> predicate)
  293. {
  294. var func = GetIdFunc<TId>();
  295. return Delete(predicate, reads => reads.Select(func));
  296. }
  297. public LuResult<IEnumerable<TDboRead>> DeleteDbo(Expression<Func<TModel, bool>> predicate)
  298. {
  299. return Delete(predicate, read => read);
  300. }
  301. public LuResult<T> DeleteSingleById<T>(TId id, Func<TDboRead, T> returnFunc)
  302. {
  303. var guid = GetId(id);
  304. if (guid == null)
  305. {
  306. return GetNotFoundResult<T>();
  307. }
  308. return Delete(GetExpression(new KeyValuePair<string, object>("id", guid)),
  309. reads => returnFunc(reads.FirstOrDefault()));
  310. }
  311. public LuResult<TId> DeleteSingleByIdId(TId id)
  312. {
  313. var func = GetIdFunc<TId>();
  314. return DeleteSingleById(id, func);
  315. }
  316. public LuResult<TDboRead> DeleteSingleByIdDbo(TId id)
  317. {
  318. return DeleteSingleById(id, read => read);
  319. }
  320. }
  321. }