DB.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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, 10, 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. finally
  151. {
  152. db.Dispose();
  153. }
  154. }
  155. }
  156. }
  157. public static void Do(Action<DB> act)
  158. {
  159. Do(db =>
  160. {
  161. act(db);
  162. return 1;
  163. });
  164. }
  165. public static void SetDefaultDbContextType(Type dbContextType)
  166. {
  167. DefaultDbContextType = dbContextType;
  168. }
  169. public static void SetDefaultDbContextType<T>()
  170. {
  171. SetDefaultDbContextType(typeof(T));
  172. }
  173. public DbContext Default
  174. {
  175. get
  176. {
  177. if (DefaultDbContextType == null)
  178. throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()");
  179. return Context(DefaultDbContextType);
  180. }
  181. }
  182. public DbContext Context(Type type)
  183. {
  184. var ctx = Contexts.Where(v => v.GetType() == type).FirstOrDefault();
  185. if (ctx == null)
  186. {
  187. ctx = Activator.CreateInstance(type) as DbContext;
  188. Contexts.Add(ctx);
  189. }
  190. return ctx;
  191. }
  192. public DbContext Context<TDbContext>()
  193. {
  194. return Context(typeof(TDbContext));
  195. }
  196. public void Dispose()
  197. {
  198. foreach (var ctx in Contexts)
  199. {
  200. ctx.Dispose();
  201. }
  202. Contexts.Clear();
  203. }
  204. }
  205. public class DB<TContext> where TContext : DbContext
  206. {
  207. public static IEnumerable<Type> EntityTypes
  208. {
  209. get
  210. {
  211. var ps = typeof(TContext).GetProperties().Where(v => v.PropertyType.Name == "DbSet`1").ToArray();
  212. var ts = ps.Select(v => v.PropertyType.GenericTypeArguments[0]).ToArray();
  213. return ts;
  214. }
  215. }
  216. /// <summary>
  217. /// 单数据库事务
  218. /// </summary>
  219. /// <typeparam name="TR"></typeparam>
  220. /// <param name="func"></param>
  221. /// <returns></returns>
  222. public static T Do<T>(Func<TContext, T> func)
  223. {
  224. using (var ctx = Activator.CreateInstance<TContext>())
  225. {
  226. var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  227. try
  228. {
  229. try
  230. {
  231. var result = func(ctx);
  232. ctx.SaveChanges();
  233. trans.Commit();
  234. return result;
  235. }
  236. catch (Exception ex)
  237. {
  238. trans.Rollback();
  239. throw ex.GetBaseException();
  240. }
  241. }
  242. catch (EntityValidationException ex)
  243. {
  244. var qty = ex.EntityValidationErrors.Count();
  245. var info = ex.EntityValidationErrors.First();
  246. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  247. Console.WriteLine(msg);
  248. throw new Exception(msg);
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// 单数据库事务
  254. /// </summary>
  255. /// <param name="act"></param>
  256. public static void Do(Action<TContext> act)
  257. {
  258. Do(ctx =>
  259. {
  260. act(ctx);
  261. return 1;
  262. });
  263. }
  264. }
  265. public class DB<TContext1, TContext2> where TContext1 : DbContext where TContext2 : DbContext
  266. {
  267. public static T Do<T>(Func<TContext1, TContext2, T> func)
  268. {
  269. using (var ctx = Activator.CreateInstance<TContext1>())
  270. {
  271. using (var ctx2 = Activator.CreateInstance<TContext2>())
  272. {
  273. var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  274. var trans2 = ctx2.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  275. try
  276. {
  277. try
  278. {
  279. var result = func(ctx, ctx2);
  280. ctx.SaveChanges();
  281. ctx2.SaveChanges();
  282. trans.Commit();
  283. trans2.Commit();
  284. return result;
  285. }
  286. catch (Exception ex)
  287. {
  288. trans.Rollback();
  289. trans2.Rollback();
  290. throw ex.GetBaseException();
  291. }
  292. }
  293. catch (EntityValidationException ex)
  294. {
  295. var qty = ex.EntityValidationErrors.Count();
  296. var info = ex.EntityValidationErrors.First();
  297. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  298. Console.WriteLine(msg);
  299. throw new Exception(msg);
  300. }
  301. }
  302. }
  303. }
  304. public static void Do(Action<TContext1, TContext2> act)
  305. {
  306. Do((ctx, ctx2) =>
  307. {
  308. act(ctx, ctx2);
  309. return 1;
  310. });
  311. }
  312. }
  313. public class DB<TContext1, TContext2, TContext3> where TContext1 : DbContext where TContext2 : DbContext where TContext3 : DbContext
  314. {
  315. public static T Do<T>(Func<TContext1, TContext2, TContext3, T> func)
  316. {
  317. using (var ctx = Activator.CreateInstance<TContext1>())
  318. {
  319. using (var ctx2 = Activator.CreateInstance<TContext2>())
  320. {
  321. using (var ctx3 = Activator.CreateInstance<TContext3>())
  322. {
  323. var trans = ctx.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  324. var trans2 = ctx2.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  325. var trans3 = ctx3.Database.BeginTransaction(System.Data.IsolationLevel.Serializable);
  326. try
  327. {
  328. try
  329. {
  330. var result = func(ctx, ctx2, ctx3);
  331. ctx.SaveChanges();
  332. ctx2.SaveChanges();
  333. ctx3.SaveChanges();
  334. trans.Commit();
  335. trans2.Commit();
  336. trans3.Commit();
  337. return result;
  338. }
  339. catch (Exception ex)
  340. {
  341. trans.Rollback();
  342. trans2.Rollback();
  343. trans3.Rollback();
  344. throw ex.GetBaseException();
  345. }
  346. }
  347. catch (EntityValidationException ex)
  348. {
  349. var qty = ex.EntityValidationErrors.Count();
  350. var info = ex.EntityValidationErrors.First();
  351. var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
  352. Console.WriteLine(msg);
  353. throw new Exception(msg);
  354. }
  355. }
  356. }
  357. }
  358. }
  359. public static void Do(Action<TContext1, TContext2, TContext3> act)
  360. {
  361. Do((ctx, ctx2, ctx3) =>
  362. {
  363. act(ctx, ctx2, ctx3);
  364. return 1;
  365. });
  366. }
  367. }
  368. }