using System; using System.Linq.Expressions; using Luticate2.Utils.Dbo; using Microsoft.EntityFrameworkCore; namespace Luticate2.Utils.DataAccess { public abstract class LuEfCrudDataAccess : LuEfDataAccess where TModel : class where TDboCreate : class where TDboRead : class where TDboUpdate : class where TDbContext : DbContext { protected LuEfCrudDataAccess(TDbContext db, DbSet table) : base(db, table) { } protected abstract TModel GetModelFromTCreate(TDboCreate obj); protected abstract TModel GetModelFromTUpdate(TDboUpdate obj); protected abstract TDboRead GetDboFromModel(TModel model); public LuResult Add(TDboCreate obj, Expression> returnFunc) { return Execute(() => { var model = GetModelFromTCreate(obj); Table.Add(model); Db.SaveChanges(); var res = returnFunc.Compile().DynamicInvoke(model); return LuResult.Ok((T) res); }); } public LuResult AddId(TDboCreate obj) { var param = Expression.Parameter(typeof(TModel), "x"); var exp = Expression.Property(param, "id"); var lambda = Expression.Lambda>(exp, param); return Add(obj, lambda); } public LuResult AddDbo(TDboCreate obj) { return Add(obj, model => GetDboFromModel(model)); } } }