123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381 |
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Transactions;
- namespace DBHelper
- {
- public class Db2 : IDisposable
- {
- public static Type DefaultDbContextType { get; private set; }
- private static readonly object LockObj = new object();
- public static T Do<T>(Func<Db2, T> func)
- {
- lock (LockObj)
- {
- using var db = new Db2();
- try
- {
- var res = func(db);
- db.Commit();
- return res;
- }
- catch (EntityValidationException ex)
- {
- var qty = ex.EntityValidationErrors.Count();
- var info = ex.EntityValidationErrors.First();
- var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- }
- }
- public static void Do(Action<Db2> act)
- {
- Do(db =>
- {
- act(db);
- return 1;
- });
- }
- public static void SetDefaultDbContextType(Type dbContextType)
- {
- DefaultDbContextType = dbContextType;
- }
- public static void SetDefaultDbContextType<T>()
- {
- SetDefaultDbContextType(typeof(T));
- }
- private Dictionary<Type, DbContext> _contexts = new Dictionary<Type, DbContext>();
- public T Context<T>() where T : DbContext
- {
- return (T)Context(typeof(T));
- }
- public DbContext Default
- {
- get
- {
- if (DefaultDbContextType == null)
- throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()");
- return Context(DefaultDbContextType);
- }
- }
- public DbContext Context(Type type)
- {
- if (_contexts.ContainsKey(type))
- return _contexts[type];
- else
- {
- var ctx = Activator.CreateInstance(type) as DbContext;
- ctx.Database.BeginTransaction();
- _contexts.Add(type, ctx);
- return ctx;
- }
- }
- private void Commit()
- {
- Exception exception = null;
- try
- {
- foreach (var ctx in _contexts.Values)
- {
- ctx.SaveChanges();
- }
- }
- catch (EntityValidationException ex)
- {
- var qty = ex.EntityValidationErrors.Count();
- var info = ex.EntityValidationErrors.First();
- var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
- Console.WriteLine(msg);
- exception = new Exception(msg);
- }
- catch (Exception ex)
- {
- exception = ex.GetBaseException();
- }
- foreach (var ctx in _contexts.Values)
- {
- try
- {
- if (exception == null)
- ctx.Database.CurrentTransaction!.Commit();
- else
- {
- ctx.Database.CurrentTransaction!.Rollback();
- throw exception;
- }
- }
- finally
- {
- ctx.Dispose();
- }
- }
- }
- public void Dispose()
- {
- foreach (var ctx in _contexts.Values)
- ctx.Dispose();
- _contexts.Clear();
- _contexts = null;
- }
- }
- public class DB : IDisposable
- {
- private readonly List<DbContext> _contexts = new List<DbContext>();
- public static Type DefaultDbContextType { get; private set; }
- public static T Do<T>(Func<DB, T> func)
- {
- var transactionOptions = new TransactionOptions
- {
- IsolationLevel = IsolationLevel.ReadCommitted,
- Timeout = new TimeSpan(0, 2, 0)
- };
- using var trans = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions);
- using var db = new DB();
- try
- {
- var res = func(db);
- trans.Complete();
- return res;
- }
- catch (EntityValidationException ex)
- {
- var qty = ex.EntityValidationErrors.Count();
- var info = ex.EntityValidationErrors.First();
- var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- finally
- {
- db.Dispose();
- }
- }
- public static void Do(Action<DB> act)
- {
- Do(db =>
- {
- act(db);
- return 1;
- });
- }
- public static void SetDefaultDbContextType(Type dbContextType)
- {
- DefaultDbContextType = dbContextType;
- }
- public static void SetDefaultDbContextType<T>()
- {
- SetDefaultDbContextType(typeof(T));
- }
- public DbContext Default
- {
- get
- {
- if (DefaultDbContextType == null)
- throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()");
- return Context(DefaultDbContextType);
- }
- }
- public DbContext Context(Type type)
- {
- var ctx = _contexts.FirstOrDefault(v => v.GetType() == type);
- if (ctx != null) return ctx;
- ctx = Activator.CreateInstance(type) as DbContext;
- _contexts.Add(ctx);
- return ctx;
- }
- public DbContext Context<TDbContext>()
- {
- return Context(typeof(TDbContext));
- }
- public void Dispose()
- {
- foreach (var ctx in _contexts)
- {
- ctx.Dispose();
- }
- _contexts.Clear();
- }
- }
- public class DB<TContext> where TContext : DbContext
- {
- public static IEnumerable<Type> EntityTypes
- {
- get
- {
- var ps = typeof(TContext).GetProperties().Where(v => v.PropertyType.Name == "DbSet`1").ToArray();
- var ts = ps.Select(v => v.PropertyType.GenericTypeArguments[0]).ToArray();
- return ts;
- }
- }
- /// <summary>
- /// 单数据库事务
- /// </summary>
- /// <typeparam name="TR"></typeparam>
- /// <param name="func"></param>
- /// <returns></returns>
- public static T Do<T>(Func<TContext, T> func)
- {
- using var ctx = Activator.CreateInstance<TContext>();
- var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
- try
- {
- try
- {
- var result = func(ctx);
- ctx.SaveChanges();
- trans.Commit();
- return result;
- }
- catch (Exception ex)
- {
- trans.Rollback();
- throw ex.GetBaseException();
- }
- }
- catch (EntityValidationException ex)
- {
- var qty = ex.EntityValidationErrors.Count();
- var info = ex.EntityValidationErrors.First();
- var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- }
- /// <summary>
- /// 单数据库事务
- /// </summary>
- /// <param name="act"></param>
- public static void Do(Action<TContext> act)
- {
- Do(ctx =>
- {
- act(ctx);
- return 1;
- });
- }
- }
- public class DB<TContext1, TContext2> where TContext1 : DbContext where TContext2 : DbContext
- {
- public static T Do<T>(Func<TContext1, TContext2, T> func)
- {
- using var ctx = Activator.CreateInstance<TContext1>();
- using var ctx2 = Activator.CreateInstance<TContext2>();
- var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
- var trans2 = ctx2.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
- try
- {
- try
- {
- var result = func(ctx, ctx2);
- ctx.SaveChanges();
- ctx2.SaveChanges();
- trans.Commit();
- trans2.Commit();
- return result;
- }
- catch (Exception ex)
- {
- trans.Rollback();
- trans2.Rollback();
- throw ex.GetBaseException();
- }
- }
- catch (EntityValidationException ex)
- {
- var qty = ex.EntityValidationErrors.Count();
- var info = ex.EntityValidationErrors.First();
- var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- }
- public static void Do(Action<TContext1, TContext2> act)
- {
- Do((ctx, ctx2) =>
- {
- act(ctx, ctx2);
- return 1;
- });
- }
- }
- public class DB<TContext1, TContext2, TContext3> where TContext1 : DbContext where TContext2 : DbContext where TContext3 : DbContext
- {
- public static T Do<T>(Func<TContext1, TContext2, TContext3, T> func)
- {
- using var ctx = Activator.CreateInstance<TContext1>();
- using var ctx2 = Activator.CreateInstance<TContext2>();
- using var ctx3 = Activator.CreateInstance<TContext3>();
- var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
- var trans2 = ctx2.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
- var trans3 = ctx3.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
- try
- {
- try
- {
- var result = func(ctx, ctx2, ctx3);
- ctx.SaveChanges();
- ctx2.SaveChanges();
- ctx3.SaveChanges();
- trans.Commit();
- trans2.Commit();
- trans3.Commit();
- return result;
- }
- catch (Exception ex)
- {
- trans.Rollback();
- trans2.Rollback();
- trans3.Rollback();
- throw ex.GetBaseException();
- }
- }
- catch (EntityValidationException ex)
- {
- var qty = ex.EntityValidationErrors.Count();
- var info = ex.EntityValidationErrors.First();
- var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- }
- public static void Do(Action<TContext1, TContext2, TContext3> act)
- {
- Do((ctx, ctx2, ctx3) =>
- {
- act(ctx, ctx2, ctx3);
- return 1;
- });
- }
- }
- }
|