DB.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Transactions;
  6. namespace DBHelper
  7. {
  8. public class DB2 : IDisposable
  9. {
  10. public static Type DefaultDbContextType { get; private set; }
  11. private static object lockObj = new object();
  12. public static T Do<T>(Func<DB2, T> func)
  13. {
  14. lock (lockObj)
  15. using (var db = new DB2())
  16. {
  17. try
  18. {
  19. var res = func(db);
  20. db.Commit();
  21. return res;
  22. }
  23. catch (EntityValidationException ex)
  24. {
  25. var qty = ex.EntityValidationErrors.Count();
  26. var info = ex.EntityValidationErrors.First();
  27. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  28. Console.WriteLine(msg);
  29. throw new Exception(msg);
  30. }
  31. }
  32. }
  33. public static void Do(Action<DB2> act)
  34. {
  35. Do(db =>
  36. {
  37. act(db);
  38. return 1;
  39. });
  40. }
  41. public static void SetDefaultDbContextType(Type dbContextType)
  42. {
  43. DefaultDbContextType = dbContextType;
  44. }
  45. public static void SetDefaultDbContextType<T>()
  46. {
  47. SetDefaultDbContextType(typeof(T));
  48. }
  49. private Dictionary<Type, DbContext> Contexts = new Dictionary<Type, DbContext>();
  50. public T Context<T>() where T : DbContext
  51. {
  52. return (T)Context(typeof(T));
  53. }
  54. public DbContext Default
  55. {
  56. get
  57. {
  58. if (DefaultDbContextType == null)
  59. throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()");
  60. return Context(DefaultDbContextType);
  61. }
  62. }
  63. public DbContext Context(Type type)
  64. {
  65. if (Contexts.ContainsKey(type))
  66. return Contexts[type];
  67. else
  68. {
  69. DbContext ctx = Activator.CreateInstance(type) as DbContext;
  70. ctx.Database.BeginTransaction();
  71. Contexts.Add(type, ctx);
  72. return ctx;
  73. }
  74. }
  75. private void Commit()
  76. {
  77. Exception exception = null;
  78. try
  79. {
  80. foreach (var ctx in Contexts.Values)
  81. {
  82. ctx.SaveChanges();
  83. }
  84. }
  85. catch (EntityValidationException ex)
  86. {
  87. var qty = ex.EntityValidationErrors.Count();
  88. var info = ex.EntityValidationErrors.First();
  89. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  90. Console.WriteLine(msg);
  91. exception = new Exception(msg);
  92. }
  93. catch (Exception ex)
  94. {
  95. exception = ex.GetBaseException();
  96. }
  97. foreach (var ctx in Contexts.Values)
  98. {
  99. try
  100. {
  101. if (exception == null)
  102. ctx.Database.CurrentTransaction.Commit();
  103. else
  104. {
  105. ctx.Database.CurrentTransaction.Rollback();
  106. throw exception;
  107. }
  108. }
  109. finally
  110. {
  111. ctx.Dispose();
  112. }
  113. }
  114. }
  115. public void Dispose()
  116. {
  117. foreach (var ctx in Contexts.Values)
  118. ctx.Dispose();
  119. Contexts.Clear();
  120. Contexts = null;
  121. }
  122. }
  123. public class DB : IDisposable
  124. {
  125. private List<DbContext> Contexts = new List<DbContext>();
  126. public static Type DefaultDbContextType { get; private set; }
  127. public static T Do<T>(Func<DB, T> func)
  128. {
  129. TransactionOptions transactionOptions = new TransactionOptions();
  130. transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
  131. transactionOptions.Timeout = new TimeSpan(0, 2, 0);
  132. using (var trans = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions))
  133. {
  134. using (var db = new DB())
  135. {
  136. try
  137. {
  138. var res = func(db);
  139. trans.Complete();
  140. return res;
  141. }
  142. catch (EntityValidationException ex)
  143. {
  144. var qty = ex.EntityValidationErrors.Count();
  145. var info = ex.EntityValidationErrors.First();
  146. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  147. Console.WriteLine(msg);
  148. throw new Exception(msg);
  149. }
  150. }
  151. }
  152. }
  153. public static void Do(Action<DB> act)
  154. {
  155. Do(db =>
  156. {
  157. act(db);
  158. return 1;
  159. });
  160. }
  161. public static void SetDefaultDbContextType(Type dbContextType)
  162. {
  163. DefaultDbContextType = dbContextType;
  164. }
  165. public static void SetDefaultDbContextType<T>()
  166. {
  167. SetDefaultDbContextType(typeof(T));
  168. }
  169. public DbContext Default
  170. {
  171. get
  172. {
  173. if (DefaultDbContextType == null)
  174. throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()");
  175. return Context(DefaultDbContextType);
  176. }
  177. }
  178. public DbContext Context(Type type)
  179. {
  180. var ctx = Contexts.Where(v => v.GetType() == type).FirstOrDefault();
  181. if (ctx == null)
  182. {
  183. ctx = Activator.CreateInstance(type) as DbContext;
  184. Contexts.Add(ctx);
  185. }
  186. return ctx;
  187. }
  188. public DbContext Context<TDbContext>()
  189. {
  190. return Context(typeof(TDbContext));
  191. }
  192. public void Dispose()
  193. {
  194. foreach (var ctx in Contexts)
  195. {
  196. ctx.Dispose();
  197. }
  198. Contexts.Clear();
  199. Contexts = null;
  200. }
  201. }
  202. public class DB<TContext> where TContext : DbContext
  203. {
  204. public static IEnumerable<Type> EntityTypes
  205. {
  206. get
  207. {
  208. var ps = typeof(TContext).GetProperties().Where(v => v.PropertyType.Name == "DbSet`1").ToArray();
  209. var ts = ps.Select(v => v.PropertyType.GenericTypeArguments[0]).ToArray();
  210. return ts;
  211. }
  212. }
  213. /// <summary>
  214. /// 单数据库事务
  215. /// </summary>
  216. /// <typeparam name="TR"></typeparam>
  217. /// <param name="func"></param>
  218. /// <returns></returns>
  219. public static T Do<T>(Func<TContext, T> func)
  220. {
  221. using (var ctx = Activator.CreateInstance<TContext>())
  222. {
  223. var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  224. try
  225. {
  226. try
  227. {
  228. var result = func(ctx);
  229. ctx.SaveChanges();
  230. trans.Commit();
  231. return result;
  232. }
  233. catch (Exception ex)
  234. {
  235. trans.Rollback();
  236. throw ex.GetBaseException();
  237. }
  238. }
  239. catch (EntityValidationException ex)
  240. {
  241. var qty = ex.EntityValidationErrors.Count();
  242. var info = ex.EntityValidationErrors.First();
  243. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  244. Console.WriteLine(msg);
  245. throw new Exception(msg);
  246. }
  247. }
  248. }
  249. /// <summary>
  250. /// 单数据库事务
  251. /// </summary>
  252. /// <param name="act"></param>
  253. public static void Do(Action<TContext> act)
  254. {
  255. Do(ctx =>
  256. {
  257. act(ctx);
  258. return 1;
  259. });
  260. }
  261. }
  262. public class DB<TContext1, TContext2> where TContext1 : DbContext where TContext2 : DbContext
  263. {
  264. public static T Do<T>(Func<TContext1, TContext2, T> func)
  265. {
  266. using (var ctx = Activator.CreateInstance<TContext1>())
  267. {
  268. using (var ctx2 = Activator.CreateInstance<TContext2>())
  269. {
  270. var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  271. var trans2 = ctx2.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  272. try
  273. {
  274. try
  275. {
  276. var result = func(ctx, ctx2);
  277. ctx.SaveChanges();
  278. ctx2.SaveChanges();
  279. trans.Commit();
  280. trans2.Commit();
  281. return result;
  282. }
  283. catch (Exception ex)
  284. {
  285. trans.Rollback();
  286. trans2.Rollback();
  287. throw ex.GetBaseException();
  288. }
  289. }
  290. catch (EntityValidationException ex)
  291. {
  292. var qty = ex.EntityValidationErrors.Count();
  293. var info = ex.EntityValidationErrors.First();
  294. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  295. Console.WriteLine(msg);
  296. throw new Exception(msg);
  297. }
  298. }
  299. }
  300. }
  301. public static void Do(Action<TContext1, TContext2> act)
  302. {
  303. Do((ctx, ctx2) =>
  304. {
  305. act(ctx, ctx2);
  306. return 1;
  307. });
  308. }
  309. }
  310. public class DB<TContext1, TContext2, TContext3> where TContext1 : DbContext where TContext2 : DbContext where TContext3 : DbContext
  311. {
  312. public static T Do<T>(Func<TContext1, TContext2, TContext3, T> func)
  313. {
  314. using (var ctx = Activator.CreateInstance<TContext1>())
  315. {
  316. using (var ctx2 = Activator.CreateInstance<TContext2>())
  317. {
  318. using (var ctx3 = Activator.CreateInstance<TContext3>())
  319. {
  320. var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  321. var trans2 = ctx2.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  322. var trans3 = ctx3.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  323. try
  324. {
  325. try
  326. {
  327. var result = func(ctx, ctx2, ctx3);
  328. ctx.SaveChanges();
  329. ctx2.SaveChanges();
  330. ctx3.SaveChanges();
  331. trans.Commit();
  332. trans2.Commit();
  333. trans3.Commit();
  334. return result;
  335. }
  336. catch (Exception ex)
  337. {
  338. trans.Rollback();
  339. trans2.Rollback();
  340. trans3.Rollback();
  341. throw ex.GetBaseException();
  342. }
  343. }
  344. catch (EntityValidationException ex)
  345. {
  346. var qty = ex.EntityValidationErrors.Count();
  347. var info = ex.EntityValidationErrors.First();
  348. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  349. Console.WriteLine(msg);
  350. throw new Exception(msg);
  351. }
  352. }
  353. }
  354. }
  355. }
  356. public static void Do(Action<TContext1, TContext2, TContext3> act)
  357. {
  358. Do((ctx, ctx2, ctx3) =>
  359. {
  360. act(ctx, ctx2, ctx3);
  361. return 1;
  362. });
  363. }
  364. }
  365. }