使用UnitOfWork模式提交更改的最佳策略是什么?是否在尝试捕获中执行?如果我需要回滚,那么在这种情况下,捕获是最好的选择?
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).");
}
答案 0 :(得分: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