使用UnitOfWork模式提交更改的最佳策略是什么?

问题描述 投票:0回答:1

使用UnitOfWork模式提交更改的最佳策略是什么?在try-catch内部进行?如果我需要回滚,那么在这种情况下捕获是最好的地方吗?

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).");
}
.net design-patterns unit-of-work
1个回答
0
投票

try / catch很好。但是,我建议不要将DbContext包装在工作单元中。实体框架已经实现了工作单元和存储库模式。具体来说,DbContext是工作单元,每个DbSet都是一个存储库。

考虑到这一点,您的代码可能如下所示:

样品

using (var context = new YourContext())
{
    using (var transaction = context.Database.BeginTransaction())
    {
        try
        {
            // your code
            context.SaveChanges();
            transaction.Commit();
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            // some logging
        }
    }
}

有关与EF交易的更多信息:

https://www.entityframeworktutorial.net/entityframework6/transaction-in-entity-framework.aspx

https://docs.microsoft.com/en-us/ef/ef6/saving/transactions

© www.soinside.com 2019 - 2024. All rights reserved.