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.

LuEfDataAccess.cs 1.4KB

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