123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq.Expressions;
- using Luticate2.Utils.Dbo.Result;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace Luticate2.Utils.DataAccess
- {
- public abstract class LuEfDataAccess<TModel, TDbContext> : LuDataAccess
- where TModel : class
- where TDbContext : DbContext
- {
- private readonly IServiceProvider _serviceProvider;
-
- protected LuEfTransactionScope TransactionScope => _serviceProvider.GetService<LuEfTransactionScope>();
-
- protected LuEfDataAccess(IServiceProvider serviceProvider)
- {
- _serviceProvider = serviceProvider;
- }
-
- protected abstract DbSet<TModel> GetTable(TDbContext db);
-
- protected virtual LuResult<T> HandleError<T>(Exception e)
- {
- return null;
- }
-
- public virtual LuResult<T> Execute<T>(Func<TDbContext, DbSet<TModel>, LuResult<T>> func)
- {
- try
- {
- var transactedDb = TransactionScope.GetTransactedDbContext<TDbContext>();
- if (transactedDb == null)
- {
- using (var db = _serviceProvider.GetService<TDbContext>())
- {
- return func(db, GetTable(db));
- }
- }
- return func(transactedDb, GetTable(transactedDb));
- }
- catch (Exception e)
- {
- var err = HandleError<T>(e);
- if (null != err)
- {
- return err;
- }
- return LuResult<T>.Error(LuStatus.DbError, e);
- }
- }
-
- public static Expression<Func<TModel, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
- {
- var param = Expression.Parameter(typeof(TModel), "x");
- Expression totalExp = null;
- foreach (var pair in keys)
- {
- var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
- totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
- }
- return Expression.Lambda<Func<TModel, bool>>(totalExp, param);
- }
-
- public bool BeginTransaction(TDbContext context, IsolationLevel? level = null)
- {
- return TransactionScope.BeginTransaction(context, level);
- }
-
- public void CommitTransaction(bool transact)
- {
- if (transact)
- {
- TransactionScope.CommitTransaction<TDbContext>();
- }
- }
-
- public void RollbackTransaction(bool transact)
- {
- if (transact)
- {
- TransactionScope.RollbackTransaction<TDbContext>();
- }
- }
-
- }
- }
|