選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

LuEfDataAccess.cs 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq.Expressions;
  4. using Luticate2.Utils.Dbo.Result;
  5. using Microsoft.EntityFrameworkCore;
  6. namespace Luticate2.Utils.DataAccess
  7. {
  8. public abstract class LuEfDataAccess<TModel, TDbContext> : LuDataAccess
  9. where TModel : class
  10. where TDbContext : DbContext
  11. {
  12. private readonly IServiceProvider _serviceProvider;
  13. protected LuEfDataAccess(IServiceProvider serviceProvider)
  14. {
  15. _serviceProvider = serviceProvider;
  16. }
  17. protected abstract DbSet<TModel> GetTable(TDbContext db);
  18. public LuResult<T> Execute<T>(Func<TDbContext, DbSet<TModel>, LuResult<T>> func)
  19. {
  20. try
  21. {
  22. using (var db = (TDbContext)_serviceProvider.GetService(typeof(TDbContext)))
  23. {
  24. var table = GetTable(db);
  25. return func(db, table);
  26. }
  27. }
  28. catch (Exception e)
  29. {
  30. return LuResult<T>.Error(LuStatus.DbError, e);
  31. }
  32. }
  33. public static Expression<Func<TModel, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
  34. {
  35. var param = Expression.Parameter(typeof(TModel), "x");
  36. Expression totalExp = null;
  37. foreach (var pair in keys)
  38. {
  39. var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
  40. totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
  41. }
  42. return Expression.Lambda<Func<TModel, bool>>(totalExp, param);
  43. }
  44. }
  45. }