using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Luticate2.Utils.Dbo.Basic; using Luticate2.Utils.Dbo.Filter; using Luticate2.Utils.Dbo.OrderBy; using Luticate2.Utils.Dbo.Result; using Luticate2.Utils.Interfaces; using Luticate2.Utils.Utils; using Microsoft.EntityFrameworkCore; namespace Luticate2.Utils.DataAccess { public abstract class LuEfCrudDataAccess : LuEfDataAccess, ILuCrudInterface 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 void EditModelFromTUpdate(TDboUpdate obj, TModel model); protected abstract TDboRead GetDboFromModel(TModel model); protected virtual Expression> GetOrderByFieldExpression(string fieldName) { fieldName = fieldName.ToSnakeCase(); if (!typeof(TModel).HasProperty(fieldName)) { return null; } var param = Expression.Parameter(typeof(TModel), "x"); var prop = Expression.Property(param, fieldName); var converted = Expression.Convert(prop, typeof(object)); var exp = Expression.Lambda>(converted, param); return exp; } protected virtual Expression> GetFilterExpression(LuFilterDbo filter) { return model => true; } protected virtual object GetId(TId id) { var s = id as string; if (s != null) { Guid guid; if (Guid.TryParse(s, out guid)) { return guid; } return null; } return id; } protected virtual IQueryable GetGetQueryable() { return Table; } protected virtual IQueryable GetEditQueryable() { return Table; } protected virtual IQueryable GetDeleteQueryable() { return Table; } protected Func GetIdFunc() { return x => ((dynamic) x).Id; } protected TModel GetModelFromTUpdate(TDboUpdate obj, TModel model) { EditModelFromTUpdate(obj, model); return model; } protected LuResult GetNotFoundResult() { return LuResult.Error(LuStatus.NotFound, typeof(TModel).Name + ": Value not found", ""); } protected IQueryable GetFilterQuery(LuFilterDbo filter) { return GetGetQueryable().Where(GetFilterExpression(filter)); } public LuResult Add(IEnumerable objs, Func, T> returnFunc) { return Execute(() => { var models = objs.Select(GetModelFromTCreate).ToList(); Table.AddRange(models); Db.SaveChanges(); foreach (var model in models) { Db.Entry(model).State = EntityState.Detached; } var dbos = models.Select(GetDboFromModel).ToList(); var res = returnFunc(dbos); return LuResult.Ok(res); }); } public LuResult Add(TDboCreate obj, Func returnFunc) { return Add(new List {obj}, list => returnFunc(list.First())); } public LuResult> AddId(IEnumerable objs) { var func = GetIdFunc(); return Add(objs, list => list.Select(func)); } public LuResult AddId(TDboCreate obj) { return AddId(new List {obj}).To(list => list.First()); } public LuResult> AddDbo(IEnumerable obj) { return Add(obj, read => read); } public LuResult AddDbo(TDboCreate obj) { return AddDbo(new List {obj}).To(list => list.First()); } public LuResult GetSingle(Expression> predicate) { return Execute(() => { var model = GetGetQueryable().AsNoTracking().FirstOrDefault(predicate); if (model == default(TModel)) { return GetNotFoundResult(); } var dbo = GetDboFromModel(model); return LuResult.Ok(dbo); }); } public LuResult GetSingleByKeys(params KeyValuePair[] keys) { return GetSingle(GetExpression(keys)); } public LuResult GetSingleById(TId id) { var guid = GetId(id); if (guid == null) { return GetNotFoundResult(); } return GetSingleByKeys(new KeyValuePair("id", guid)); } public LuResult> GetMultiple(Func, IOrderedQueryable> orderBy, Expression> predicate, int page = 0, int perPage = int.MaxValue, params Func, IOrderedQueryable>[] otherOrderBy) { return Execute(() => { var queryable = GetGetQueryable(); var count = queryable.Count(predicate); var ordered = orderBy(queryable); foreach (var func in otherOrderBy) { ordered = func(ordered); } var data = ordered.Where(predicate).Skip(page * perPage).Take(perPage).AsNoTracking().Select(GetDboFromModel).ToList(); var result = new LuPaginatedDbo { Count = count, Data = data }; return LuResult>.Ok(result); }); } public LuResult> GetMultiple(Expression> orderBy, Expression> predicate, int page = 0, int perPage = int.MaxValue, params Expression>[] otherOrderBy) { return GetMultiple(table => table.OrderBy(orderBy), predicate, page, perPage, otherOrderBy.Select>, Func, IOrderedQueryable>>(expression => (t => t.ThenBy(expression))).ToArray()); } public LuResult> GetMultiple(Func, IOrderedQueryable> orderBy, int page = 0, int perPage = int.MaxValue, params Func, IOrderedQueryable>[] otherOrderBy) { return GetMultiple(orderBy, x => true, page, perPage, otherOrderBy); } public LuResult> GetMultiple(Expression> orderBy, int page = 0, int perPage = int.MaxValue, params Expression>[] otherOrderBy) { return GetMultiple(orderBy, x => true, page, perPage, otherOrderBy); } public LuResult> GetMultiple(LuOrderByDbo orderBy, IQueryable queryable, int page = 0, int perPage = int.MaxValue) { return Execute(() => { var count = queryable.Count(); IOrderedQueryable ordered = null; foreach (var field in orderBy.Fields) { var exp = GetOrderByFieldExpression(field.Name); if (exp == null) { return LuResult>.Error(LuStatus.InputError, string.Format("LuEfCrudDataAccess: {0}", field.Name), "Invalid order by field"); } if (ordered != null) { ordered = field.Asc ? ordered.ThenBy(exp) : ordered.ThenByDescending(exp); } else { ordered = field.Asc ? queryable.OrderBy(exp) : queryable.OrderByDescending(exp); } } var data = ordered.Skip(page * perPage).Take(perPage).AsNoTracking().Select(GetDboFromModel).ToList(); var result = new LuPaginatedDbo { Count = count, Data = data }; return LuResult>.Ok(result); }); } public LuResult> GetMultiple(LuOrderByDbo orderBy, LuFilterDbo filter, int page = 0, int perPage = int.MaxValue) { return GetMultiple(orderBy, GetFilterQuery(filter), page, perPage); } public LuResult> GetMultiple(LuOrderByDbo orderBy, int page = 0, int perPage = int.MaxValue) { return GetMultiple(orderBy, GetGetQueryable(), page, perPage); } public LuResult Edit(Expression> predicate, Action update, Func, T> returnFunc) { return Execute(() => { var models = GetEditQueryable().Where(predicate).AsNoTracking(); var editedDbos = new List(); foreach (var model in models) { update(model); editedDbos.Add(GetDboFromModel(model)); Db.Entry(model).State = EntityState.Modified; } Db.SaveChanges(); var res = returnFunc(editedDbos); return LuResult.Ok(res); }); } public LuResult> EditId(Expression> predicate, Action update) { var func = GetIdFunc(); return Edit(predicate, update, reads => reads.Select(func)); } public LuResult> EditDbo(Expression> predicate, Action update) { return Edit(predicate, update, read => read); } public LuResult EditSingleById(TId id, Action update, Func returnFunc) { var guid = GetId(id); if (guid == null) { return GetNotFoundResult(); } return Edit(GetExpression(new KeyValuePair("id", guid)), update, list => returnFunc(list.FirstOrDefault())); } public LuResult EditSingleByIdId(TId id, Action update) { return EditSingleById(id, update, GetIdFunc()); } public LuResult EditSingleByIdDbo(TId id, Action update) { return EditSingleById(id, update, read => read); } public LuResult EditSingleById(TId id, TDboUpdate update, Func returnFunc) { var guid = GetId(id); if (guid == null) { return GetNotFoundResult(); } return Edit(GetExpression(new KeyValuePair("id", guid)), model => EditModelFromTUpdate(update, model), list => returnFunc(list.FirstOrDefault())); } public LuResult EditSingleByIdId(TId id, TDboUpdate update) { return EditSingleById(id, update, GetIdFunc()); } public LuResult EditSingleByIdDbo(TId id, TDboUpdate update) { return EditSingleById(id, update, read => read); } public LuResult Delete(Expression> predicate, Func, T> returnFunc) { return Execute(() => { var models = GetDeleteQueryable().Where(predicate).AsNoTracking().ToList(); Table.RemoveRange(models); Db.SaveChanges(); var dbos = models.Select(GetDboFromModel); return LuResult.Ok(returnFunc(dbos)); }); } public LuResult> DeleteId(Expression> predicate) { var func = GetIdFunc(); return Delete(predicate, reads => reads.Select(func)); } public LuResult> DeleteDbo(Expression> predicate) { return Delete(predicate, read => read); } public LuResult DeleteSingleById(TId id, Func returnFunc) { var guid = GetId(id); if (guid == null) { return GetNotFoundResult(); } return Delete(GetExpression(new KeyValuePair("id", guid)), reads => returnFunc(reads.FirstOrDefault())); } public LuResult DeleteSingleByIdId(TId id) { var func = GetIdFunc(); return DeleteSingleById(id, func); } public LuResult DeleteSingleByIdDbo(TId id) { return DeleteSingleById(id, read => read); } } }