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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. protected readonly TDbContext Db;
  13. protected readonly DbSet<TModel> Table;
  14. protected LuEfDataAccess(TDbContext db, DbSet<TModel> table)
  15. {
  16. Db = db;
  17. Table = table;
  18. }
  19. public LuResult<T> Execute<T>(Func<LuResult<T>> func)
  20. {
  21. try
  22. {
  23. return func();
  24. }
  25. catch (Exception e)
  26. {
  27. return LuResult<T>.Error(LuStatus.DbError, e);
  28. }
  29. }
  30. public static Expression<Func<TModel, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
  31. {
  32. var param = Expression.Parameter(typeof(TModel), "x");
  33. Expression totalExp = null;
  34. foreach (var pair in keys)
  35. {
  36. var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
  37. totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
  38. }
  39. return Expression.Lambda<Func<TModel, bool>>(totalExp, param);
  40. }
  41. }
  42. }