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.

LuEfCrudDataAccess.cs 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Linq.Expressions;
  3. using Luticate2.Utils.Dbo;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Luticate2.Utils.DataAccess
  6. {
  7. public abstract class LuEfCrudDataAccess<TModel, TDboCreate, TDboRead, TDboUpdate, TDbContext> : LuEfDataAccess<TModel, TDbContext>
  8. where TModel : class
  9. where TDboCreate : class
  10. where TDboRead : class
  11. where TDboUpdate : class
  12. where TDbContext : DbContext
  13. {
  14. protected LuEfCrudDataAccess(TDbContext db, DbSet<TModel> table) : base(db, table)
  15. {
  16. }
  17. protected abstract TModel GetModelFromTCreate(TDboCreate obj);
  18. protected abstract TModel GetModelFromTUpdate(TDboUpdate obj);
  19. protected abstract TDboRead GetDboFromModel(TModel model);
  20. public LuResult<T> Add<T>(TDboCreate obj, Expression<Func<TModel, T>> returnFunc)
  21. {
  22. return Execute(() =>
  23. {
  24. var model = GetModelFromTCreate(obj);
  25. Table.Add(model);
  26. Db.SaveChanges();
  27. var res = returnFunc.Compile().DynamicInvoke(model);
  28. return LuResult<T>.Ok((T) res);
  29. });
  30. }
  31. public LuResult<string> AddId(TDboCreate obj)
  32. {
  33. var param = Expression.Parameter(typeof(TModel), "x");
  34. var exp = Expression.Property(param, "id");
  35. var lambda = Expression.Lambda<Func<TModel, string>>(exp, param);
  36. return Add(obj, lambda);
  37. }
  38. public LuResult<TDboRead> AddDbo(TDboCreate obj)
  39. {
  40. return Add(obj, model => GetDboFromModel(model));
  41. }
  42. }
  43. }