Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

LuEfCrudDataAccess.cs 13KB

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