Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Note: methods are async for conventions, not because
- // they're truly async
- public interface IUnitOfWork
- {
- Task Begin();
- // The Task<int> is the numbers of rows affected by this commit
- Task<int> Commit();
- Task Rollback();
- }
- public interface IWriteableRepository<T>
- where T : class
- {
- EntityEntry<T> Insert(T item);
- // Other CRUD methods removed for brevity; they're
- // of similar signatures
- }
- await this.UnitOfWork.Begin();
- this.Repository.Insert(someEntity);
- var rows = await this.UnitOfWork.Commit();
- public class UnitOfWork : IUnitOfWork
- {
- public UnitOfWork(DbContext context)
- {
- this.Context = context;
- }
- private DbContext Context { get; set; }
- private TransactionScope Transaction { get; set; }
- public async Task Begin()
- {
- if (this.Scope == null)
- {
- this.Transaction = await this.Context
- .Database
- .BeginTransactionAsync();
- }
- }
- public async Task<int> Commit()
- {
- if (this.Scope != null)
- {
- var rows = await this.Context.SaveChangesAsync(false);
- this.Scope.Commit();
- this.Context.AcceptAllChanges();
- return rows;
- }
- }
- public Task Rollback()
- {
- if (this.Scope != null)
- {
- this.Scope.Rollback();
- this.Scope.Dispose();
- this.Scope = null;
- }
- return Task.CompletedTask;
- }
- }
Add Comment
Please, Sign In to add comment