using System; using System.Collections.Generic; using System.Linq; 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 AddGuid(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 AddGuidStr(TDboCreate obj) { var res = AddGuid(obj); if (!res) { return res.To(); } return LuResult.Ok(res.Data.ToString()); } 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)); } public LuResult GetSingle(Expression> predicate) { return Execute(() => { var model = Table.FirstOrDefault(predicate); if (model == null) { return LuResult.Error(LuStatus.NotFound, typeof(TModel).Name + ": Value not found", ""); } return LuResult.Ok(GetDboFromModel(model)); }); } public LuResult GetSingleByKeys(params KeyValuePair[] keys) { return GetSingle(GetExpression(keys)); } public LuResult GetSingleByGuid(Guid id) { return GetSingleByKeys(new KeyValuePair("id", id)); } public LuResult GetSingleByGuidStr(string id) { return GetSingleByGuid(new Guid(id)); } public LuResult GetSingleById(long id) { return GetSingleByKeys(new KeyValuePair("id", id)); } } }