Tell EntityFramework 6.x , please, how to implement Rollback using EntityFramework 6.x , as well as the Unit of work pattern. For this there is a class interface IUnitOfWork

 public interface IUnitOfWork : IDisposable { void Commit(); // void Rollback(); } 

and class - UnitOfWork

  public class UnitOfWork : IUnitOfWork { public DbContext Context { get; private set; } public UnitOfWork(DbContext context) { Context = context; } public void Commit() { if (Context != null) { Context.SaveChanges(); } } public void Dispose() { if (Context != null) { Context.Dispose(); } } } 

I know that at the T-SQL level, this is defined as follows:

 BEGIN TRANSACTION // ΠΎΠΏΠ΅Ρ€Π°Ρ†ΠΈΠΈ взаимодСйствия IF (@@error <> 0) ROLLBACK COMMIT 

UPD

It is planned to be used as

 try { repository.Delete(...); unitOfWork.Commit(); } catch { unitOfWork.Rollback(); // рСгистрация ошибки } 

    2 answers 2

    Just call Dispose without calling Commit. Or manually in finally, or using using:

     using (var unitOfWork = new UnitOfWork(context)) { repository.Delete(...); unitOfWork.Commit(); } catch { // рСгистрация ошибки } 

    If an error occurs before the SaveChanges call, the changes will simply be thrown away by the Dispose of the wrapper and context.

    If an error occurs during the execution of SaveChanges, then the SQL transaction will be rolled back, which EF opens at the beginning of SaveChanges and commits after all changes have been saved.

    Just do not forget that in fact the context in EF is the ready implementation of the Unit Of Work + Repository patterns. And your UnitOfWork is just a proxy wrapper that UoW itself does not implement - it just separates the UoW interface from the repository.

    Therefore, your context should live for you no longer than a wrapper, so you cannot (and should not) reuse it for another instance of UnitOfWork.

    • Can you explain the last paragraph? - Vadim Prokopchuk
    • And if there is no error and you need to cancel the transaction? Already watch logs? - Vadim Prokopchuk
    • @VadimProkopchuk your wrapper when you call Dispose destroys the context that was passed to it. Those. you cannot create uow1 on top of some kind of context1, destroy uow1, and then create uow2 on top of the same context1 - it will fall. - PashaPash ♦
    • @VadimProkopchuk if it is called Commit / SaveChanges - then the transaction cannot be rolled back. Because transactions in SQL Server - Durable, they can not be "uncommitted". If SaveChanges was not called, simply do not call it, and all changes are simply discarded. - PashaPash ♦

    A similar question was asked by a user in English StackOverflow: How to rollback a transaction in the Entity Framework . After conducting an experiment, he found out that in case of an error that occurs when calling the DbContext.SaveChanges method, the Entity Framework automatically rolls back all changes.