您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

LuEfCrudDataAccess.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using Luticate2.Auth.Utils.Business.Converters;
  6. using Luticate2.Auth.Utils.Business.Converters.ExpressionConverter;
  7. using Luticate2.Auth.Utils.Dbo;
  8. using Luticate2.Auth.Utils.Dbo.Fields;
  9. using Luticate2.Auth.Utils.Dbo.Pagination;
  10. using Luticate2.Auth.Utils.Dbo.Result;
  11. using Luticate2.Auth.Utils.Interfaces;
  12. using Microsoft.EntityFrameworkCore;
  13. using Microsoft.Extensions.DependencyInjection;
  14. namespace Luticate2.Auth.Utils.DataAccess.Crud
  15. {
  16. public class LuEfCrudDataAccess<TDbo, TModel, TDbContext> : ILuCrud<TDbo>
  17. where TModel : class
  18. where TDbContext : DbContext
  19. where TDbo : class
  20. {
  21. protected IServiceProvider ServiceProvider { get; }
  22. protected ILuConvertersAllocator ConvertersAllocator { get; }
  23. protected ILuConvertersTypeConverter ConvertersTypeConverter { get; }
  24. public LuEfCrudDataAccess(IServiceProvider serviceProvider)
  25. {
  26. ServiceProvider = serviceProvider;
  27. ConvertersAllocator = ServiceProvider.GetRequiredService<ILuConvertersAllocator>(); // TODO Make a DbContext or DataAccess specific ILuConvertersAllocator (in case of multiple DbContext)
  28. ConvertersTypeConverter = ServiceProvider.GetRequiredService<ILuConvertersTypeConverter>(); // TODO same as above
  29. }
  30. protected virtual LuConvertersOptions GetOptions()
  31. {
  32. return new LuConvertersOptions
  33. {
  34. Allocator = ConvertersAllocator,
  35. Parameters = new Dictionary<ParameterExpression, Expression>(),
  36. TypeConverter = ConvertersTypeConverter
  37. };
  38. }
  39. protected virtual LuResult<TTypeTo> Convert<TTypeTo>(LuPartialFieldsDbo partialResponse, object dbo, LuConvertersOptions options) where TTypeTo : class
  40. {
  41. var typeTo = dbo.GetType();
  42. var converterType = typeof(ILuObjectConverter<,>);
  43. var gConverterType = converterType.MakeGenericType(typeTo, typeof(TTypeTo));
  44. var converter = (ILuObjectConverter) ServiceProvider.GetService(gConverterType);
  45. if (converter == null)
  46. {
  47. return LuResult<TTypeTo>.Error(LuStatus.InternalError.ToInt(),
  48. $"Could not get service: {nameof(ILuObjectConverter)}<{typeof(TDbo).Name}, {typeof(TTypeTo).Name}>");
  49. }
  50. var dstObjResult = options.Allocator.GetInstance(typeof(TTypeTo));
  51. if (!dstObjResult)
  52. {
  53. return dstObjResult.To<TTypeTo>();
  54. }
  55. var dstObj = dstObjResult.Data;
  56. var result = converter.Convert(dbo, dstObj, new LuFieldDbo(), partialResponse, options);
  57. return result.Select(o => o as TTypeTo);
  58. }
  59. protected virtual LuResult<IList<TTypeTo>> Convert<TTypeTo>(LuPartialFieldsDbo partialResponse, IEnumerable<object> dbos, LuConvertersOptions options) where TTypeTo : class
  60. {
  61. var dboList = new List<TTypeTo>();
  62. foreach (var model in dbos)
  63. {
  64. var dboResult = Convert<TTypeTo>(partialResponse, model, options);
  65. if (!dboResult)
  66. {
  67. return dboResult.To<IList<TTypeTo>>();
  68. }
  69. var dbo = dboResult.Data;
  70. dboList.Add(dbo);
  71. }
  72. return LuResult<IList<TTypeTo>>.Ok(dboList);
  73. }
  74. protected virtual LuResult<T> HandleError<T>(Exception e)
  75. {
  76. return LuResult<T>.Error(LuStatus.DbError.ToInt(), e);
  77. }
  78. protected LuResult<T> Execute<T>(Func<TDbContext, DbSet<TModel>, LuResult<T>> action)
  79. {
  80. try
  81. {
  82. using (var db = ServiceProvider.GetService<TDbContext>())
  83. {
  84. return action(db, db.Set<TModel>());
  85. }
  86. }
  87. catch (Exception e)
  88. {
  89. var result = HandleError<T>(e);
  90. return result;
  91. }
  92. }
  93. protected virtual LuResult<IQueryable<TModel>> Include(LuPartialFieldsDbo partialResponse, IQueryable<TModel> queryable)
  94. {
  95. return LuResult<IQueryable<TModel>>.Ok(queryable);
  96. }
  97. protected virtual LuResult<IQueryable<TModel>> Filter(LuFilterDbo filter, IQueryable<TModel> queryable, LuConvertersOptions options)
  98. {
  99. if (filter.Expression == null)
  100. {
  101. return LuResult<IQueryable<TModel>>.Ok(queryable);
  102. }
  103. var lambdaDbo = filter.Expression as Expression<Func<TDbo, bool>>;
  104. var converter = new LuExpressionConverterVisitor(options, ServiceProvider);
  105. var lambdaModel = converter.Visit(lambdaDbo) as Expression<Func<TModel, bool>>;// TODO Handle errors
  106. return LuResult<IQueryable<TModel>>.Ok(queryable.Where(lambdaModel));
  107. }
  108. protected virtual LuResult<IQueryable<TModel>> OrderByField(LuOrderByFieldDbo orderByField, IQueryable<TModel> queryable, LuConvertersOptions options)
  109. {
  110. var lambdaDbo = orderByField.Expression as Expression<Func<TDbo, object>>;
  111. var converter = new LuExpressionConverterVisitor(options, ServiceProvider);
  112. var lambdaModelNoConvert = converter.Visit(lambdaDbo) as LambdaExpression;// TODO Handle errors
  113. var lambdaModel = Expression.Lambda<Func<TModel, object>>(lambdaModelNoConvert.Body, lambdaModelNoConvert.Parameters);
  114. IOrderedQueryable<TModel> ordered;
  115. if (queryable is IOrderedQueryable<TModel> orderedQueryable)
  116. {
  117. if (orderByField.Asc)
  118. {
  119. ordered = orderedQueryable.ThenBy(lambdaModel);
  120. }
  121. else
  122. {
  123. ordered = orderedQueryable.ThenByDescending(lambdaModel);
  124. }
  125. }
  126. else
  127. {
  128. if (orderByField.Asc)
  129. {
  130. ordered = queryable.OrderBy(lambdaModel);
  131. }
  132. else
  133. {
  134. ordered = queryable.OrderByDescending(lambdaModel);
  135. }
  136. }
  137. return LuResult<IQueryable<TModel>>.Ok(ordered);
  138. }
  139. protected virtual LuResult<IQueryable<TModel>> OrderBy(LuOrderByDbo orderBy, IQueryable<TModel> queryable, LuConvertersOptions options)
  140. {
  141. var ordered = queryable;
  142. foreach (var field in orderBy.OrderByFields)
  143. {
  144. var orderedResult = OrderByField(field, ordered, options);
  145. if (!orderedResult)
  146. {
  147. return orderedResult.To<IQueryable<TModel>>();
  148. }
  149. ordered = orderedResult.Data;
  150. }
  151. return LuResult<IQueryable<TModel>>.Ok(ordered ?? queryable);
  152. }
  153. protected virtual LuResult<IQueryable<TModel>> Paginate(int page, int perPage, IQueryable<TModel> queryable)
  154. {
  155. var paginated = queryable.Skip(page * perPage).Take(perPage);
  156. return LuResult<IQueryable<TModel>>.Ok(paginated);
  157. }
  158. protected virtual LuResult<LuPaginatedDbo<TModel>> Paginate(LuPaginatedParamsDbo paginationParams, LuPartialFieldsDbo partialResponse, IQueryable<TModel> set, LuConvertersOptions options)
  159. {
  160. var includeResult = Include(partialResponse, set);
  161. if (!includeResult)
  162. {
  163. return includeResult.To<LuPaginatedDbo<TModel>>();
  164. }
  165. var included = includeResult.Data;
  166. var orderByResult = OrderBy(paginationParams.OrderBy, included, options);
  167. if (!orderByResult)
  168. {
  169. return orderByResult.To<LuPaginatedDbo<TModel>>();
  170. }
  171. var ordered = orderByResult.Data;
  172. var filteredResult = Filter(paginationParams.Filter, ordered, options);
  173. if (!filteredResult)
  174. {
  175. return filteredResult.To<LuPaginatedDbo<TModel>>();
  176. }
  177. var filtered = filteredResult.Data;
  178. var count = filtered.Count();
  179. var paginatedResult = Paginate(paginationParams.Page, paginationParams.PerPage, filtered);
  180. if (!paginatedResult)
  181. {
  182. return paginatedResult.To<LuPaginatedDbo<TModel>>();
  183. }
  184. var paginated = paginatedResult.Data;
  185. var paginatedData = new LuPaginatedDbo<TModel>
  186. {
  187. Data = paginated.ToList(),
  188. Count = count
  189. };
  190. return LuResult<LuPaginatedDbo<TModel>>.Ok(paginatedData);
  191. }
  192. public virtual LuResult<IList<TDbo>> Create(LuPartialFieldsDbo partialResponse, LuPartialFieldsDbo partialInput, IEnumerable<object> dbos)
  193. {
  194. var options = GetOptions();
  195. var addedDbos = new List<TDbo>();
  196. var addedModels = new List<TModel>();
  197. var createResult = Execute((context, set) =>
  198. {
  199. foreach (var dbo in dbos)
  200. {
  201. var convertResult = Convert<TModel>(partialInput, dbo, options);
  202. if (!convertResult)
  203. {
  204. return convertResult.To<bool>();
  205. }
  206. var model = convertResult.Data;
  207. set.Add(model);
  208. addedModels.Add(model);
  209. }
  210. context.SaveChanges();
  211. return LuResult<bool>.Ok(true);
  212. });
  213. if (!createResult)
  214. {
  215. return createResult.To<IList<TDbo>>();
  216. }
  217. foreach (var addedModel in addedModels)
  218. {
  219. var convertResult = Convert<TDbo>(partialResponse, addedModel, options);
  220. if (!convertResult)
  221. {
  222. return convertResult.To<IList<TDbo>>();
  223. }
  224. addedDbos.Add(convertResult.Data);
  225. }
  226. return LuResult<IList<TDbo>>.Ok(addedDbos);
  227. }
  228. public virtual LuResult<LuPaginatedDbo<TDbo>> Read(LuPartialFieldsDbo partialResponse, LuPaginatedParamsDbo paginationParams)
  229. {
  230. var result = Execute((context, set) =>
  231. {
  232. var options = GetOptions();
  233. var paginatedResult = Paginate(paginationParams, partialResponse, set, options);
  234. if (!paginatedResult)
  235. {
  236. return paginatedResult.To<LuPaginatedDbo<TDbo>>();
  237. }
  238. var paginated = paginatedResult.Data;
  239. var dboListResult = Convert<TDbo>(partialResponse, paginated.Data, options);
  240. if (!dboListResult)
  241. {
  242. return dboListResult.To<LuPaginatedDbo<TDbo>>();
  243. }
  244. var dboList = dboListResult.Data;
  245. var paginatedData = new LuPaginatedDbo<TDbo>
  246. {
  247. Count = paginated.Count,
  248. Data = dboList
  249. };
  250. return LuResult<LuPaginatedDbo<TDbo>>.Ok(paginatedData);
  251. });
  252. return result;
  253. }
  254. public virtual LuResult<IList<TDbo>> Update(LuPartialFieldsDbo partialResponse, LuPartialFieldsDbo partialInput, IEnumerable<object> dbos)
  255. {
  256. throw new NotImplementedException();
  257. }
  258. public virtual LuResult<LuPaginatedDbo<TDbo>> Delete(LuPartialFieldsDbo partialResponse, LuPaginatedParamsDbo paginationParams)
  259. {
  260. var res = Execute((context, set) =>
  261. {
  262. var options = GetOptions();
  263. var paginatedResult = Paginate(paginationParams, partialResponse, set, options);
  264. if (!paginatedResult)
  265. {
  266. return paginatedResult.To<LuPaginatedDbo<TDbo>>();
  267. }
  268. var paginated = paginatedResult.Data;
  269. var dboListResult = Convert<TDbo>(partialResponse, paginated.Data, options);
  270. if (!dboListResult)
  271. {
  272. return dboListResult.To<LuPaginatedDbo<TDbo>>();
  273. }
  274. var dboList = dboListResult.Data;
  275. set.RemoveRange(paginated.Data);
  276. context.SaveChanges();
  277. var paginatedData = new LuPaginatedDbo<TDbo>
  278. {
  279. Count = paginated.Count,
  280. Data = dboList
  281. };
  282. return LuResult<LuPaginatedDbo<TDbo>>.Ok(paginatedData);
  283. });
  284. return res;
  285. }
  286. }
  287. }