You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuEfTransactionScope.cs 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.Extensions.DependencyInjection;
  6. namespace Luticate2.Utils.DataAccess
  7. {
  8. public class LuEfTransactionScope
  9. {
  10. protected IDictionary<Type, DbContext> Contexts;
  11. private readonly IServiceProvider _serviceProvider;
  12. public LuEfTransactionScope(IServiceProvider serviceProvider)
  13. {
  14. _serviceProvider = serviceProvider;
  15. Contexts = new Dictionary<Type, DbContext>();
  16. }
  17. public TDbContext GetTransactedDbContext<TDbContext>()
  18. where TDbContext : DbContext
  19. {
  20. if (Contexts.ContainsKey(typeof(TDbContext)))
  21. {
  22. return (TDbContext) Contexts[typeof(TDbContext)];
  23. }
  24. return null;
  25. }
  26. public bool BeginTransaction<TDbContext>(TDbContext dbContext, IsolationLevel? level = null)
  27. where TDbContext : DbContext
  28. {
  29. if (dbContext == null)
  30. {
  31. dbContext = GetTransactedDbContext<TDbContext>();
  32. if (dbContext == null)
  33. {
  34. dbContext = _serviceProvider.GetService<TDbContext>();
  35. }
  36. }
  37. if (!Contexts.Contains(new KeyValuePair<Type, DbContext>(typeof(TDbContext), dbContext)))
  38. {
  39. Contexts.Add(typeof(TDbContext), dbContext);
  40. }
  41. if (dbContext.Database.CurrentTransaction != null)
  42. {
  43. return false;
  44. }
  45. if (level == null)
  46. {
  47. dbContext.Database.BeginTransaction();
  48. }
  49. else
  50. {
  51. dbContext.Database.BeginTransaction(level.Value);
  52. }
  53. return true;
  54. }
  55. public void CommitTransaction<TDbContext>()
  56. where TDbContext : DbContext
  57. {
  58. try
  59. {
  60. GetTransactedDbContext<TDbContext>().Database.CommitTransaction();
  61. }
  62. finally
  63. {
  64. Contexts.Remove(typeof(TDbContext));
  65. }
  66. }
  67. public void RollbackTransaction<TDbContext>()
  68. where TDbContext : DbContext
  69. {
  70. try
  71. {
  72. GetTransactedDbContext<TDbContext>().Database.RollbackTransaction();
  73. }
  74. finally
  75. {
  76. Contexts.Remove(typeof(TDbContext));
  77. }
  78. }
  79. }
  80. }