dimanche 21 avril 2019

What is the best strategy to commit the changes using the UnitOfWork pattern?

What is the best strategy to commit the changes using the UnitOfWork pattern? Doing it inside a try-catch? If I need to rollback , the catch is the best place to do it in that case?

public void Commit() {
            _context.SaveChanges();
}

public void Rollback() {
            _context
                .ChangeTracker
                .Entries()
                .Where(entry => entry.State != EntityState.Unchanged)
                .ToList()
                .ForEach(entry => {
                    switch (entry.State)
                    {
                        // Under the covers, changing the state of an entity from  
                        // Modified to Unchanged first sets the values of all  
                        // properties to the original values that were read from  
                        // the database when it was queried, and then marks the  
                        // entity as Unchanged. This will also reject changes to  
                        // FK relationships since the original value of the FK  
                        // will be restored. 
                        case EntityState.Modified:
                            entry.State = EntityState.Unchanged;
                            break;
                        case EntityState.Added:
                            entry.State = EntityState.Detached;
                            break;
                        // If the EntityState is the Deleted, reload the date from the database.   
                        case EntityState.Deleted:
                            entry.Reload();
                            break;
                        default: break;
                    }
                });
}

try { 
  UnitOfWorkRPOMain.Commit();
}
  catch (Exception ex) {
  UnitOfWorkRPOMain.Rollback();
  Logger.Error(baseLog + "Error - ex.Message).");
}

Aucun commentaire:

Enregistrer un commentaire