123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- 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<TModel, TDboCreate, TDboRead, TDboUpdate, TDbContext> : LuEfDataAccess<TModel, TDbContext>
- where TModel : class
- where TDboCreate : class
- where TDboRead : class
- where TDboUpdate : class
- where TDbContext : DbContext
- {
- protected LuEfCrudDataAccess(TDbContext db, DbSet<TModel> table) : base(db, table)
- {
- }
-
- protected abstract TModel GetModelFromTCreate(TDboCreate obj);
-
- protected abstract TModel GetModelFromTUpdate(TDboUpdate obj);
-
- protected abstract TDboRead GetDboFromModel(TModel model);
-
- public LuResult<T> Add<T>(TDboCreate obj, Expression<Func<TModel, T>> returnFunc)
- {
- return Execute(() =>
- {
- var model = GetModelFromTCreate(obj);
- Table.Add(model);
- Db.SaveChanges();
- var res = returnFunc.Compile().DynamicInvoke(model);
- return LuResult<T>.Ok((T) res);
- });
- }
-
- public LuResult<Guid> AddGuid(TDboCreate obj)
- {
- var param = Expression.Parameter(typeof(TModel), "x");
- var exp = Expression.Property(param, "id");
- var lambda = Expression.Lambda<Func<TModel, Guid>>(exp, param);
- return Add(obj, lambda);
- }
-
- public LuResult<string> AddGuidStr(TDboCreate obj)
- {
- var res = AddGuid(obj);
- if (!res)
- {
- return res.To<string>();
- }
- return LuResult<string>.Ok(res.Data.ToString());
- }
-
- public LuResult<long> AddId(TDboCreate obj)
- {
- var param = Expression.Parameter(typeof(TModel), "x");
- var exp = Expression.Property(param, "id");
- var lambda = Expression.Lambda<Func<TModel, long>>(exp, param);
- return Add(obj, lambda);
- }
-
- public LuResult<TDboRead> AddDbo(TDboCreate obj)
- {
- return Add(obj, model => GetDboFromModel(model));
- }
-
- public LuResult<TDboRead> GetSingle(Expression<Func<TModel, bool>> predicate)
- {
- return Execute(() =>
- {
- var model = Table.FirstOrDefault(predicate);
- if (model == null)
- {
- return LuResult<TDboRead>.Error(LuStatus.NotFound, typeof(TModel).Name + ": Value not found", "");
- }
- return LuResult<TDboRead>.Ok(GetDboFromModel(model));
- });
- }
-
- public LuResult<TDboRead> GetSingleByKeys(params KeyValuePair<string, object>[] keys)
- {
- return GetSingle(GetExpression(keys));
- }
-
- public LuResult<TDboRead> GetSingleByGuid(Guid id)
- {
- return GetSingleByKeys(new KeyValuePair<string, object>("id", id));
- }
-
- public LuResult<TDboRead> GetSingleByGuidStr(string id)
- {
- return GetSingleByGuid(new Guid(id));
- }
-
- public LuResult<TDboRead> GetSingleById(long id)
- {
- return GetSingleByKeys(new KeyValuePair<string, object>("id", id));
- }
- }
- }
|