Guest User

Untitled

a guest
Dec 11th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. // Note: methods are async for conventions, not because
  2. // they're truly async
  3. public interface IUnitOfWork
  4. {
  5. Task Begin();
  6.  
  7. // The Task<int> is the numbers of rows affected by this commit
  8. Task<int> Commit();
  9.  
  10. Task Rollback();
  11. }
  12.  
  13. public interface IWriteableRepository<T>
  14. where T : class
  15. {
  16. EntityEntry<T> Insert(T item);
  17.  
  18. // Other CRUD methods removed for brevity; they're
  19. // of similar signatures
  20. }
  21.  
  22. await this.UnitOfWork.Begin();
  23.  
  24. this.Repository.Insert(someEntity);
  25.  
  26. var rows = await this.UnitOfWork.Commit();
  27.  
  28. public class UnitOfWork : IUnitOfWork
  29. {
  30. public UnitOfWork(DbContext context)
  31. {
  32. this.Context = context;
  33. }
  34.  
  35. private DbContext Context { get; set; }
  36.  
  37. private TransactionScope Transaction { get; set; }
  38.  
  39. public async Task Begin()
  40. {
  41. if (this.Scope == null)
  42. {
  43. this.Transaction = await this.Context
  44. .Database
  45. .BeginTransactionAsync();
  46. }
  47. }
  48.  
  49. public async Task<int> Commit()
  50. {
  51. if (this.Scope != null)
  52. {
  53. var rows = await this.Context.SaveChangesAsync(false);
  54.  
  55. this.Scope.Commit();
  56.  
  57. this.Context.AcceptAllChanges();
  58.  
  59. return rows;
  60. }
  61. }
  62.  
  63. public Task Rollback()
  64. {
  65. if (this.Scope != null)
  66. {
  67. this.Scope.Rollback();
  68. this.Scope.Dispose();
  69.  
  70. this.Scope = null;
  71. }
  72.  
  73. return Task.CompletedTask;
  74. }
  75. }
Add Comment
Please, Sign In to add comment