1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- 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);
-
- 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)
- {
- 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>();
- }
- }
-
- }
- }
|