【发布时间】:2018-06-14 10:36:55
【问题描述】:
给定一个带有 2 个随后打开的 DbContext 的 TransactionScope,第一个上下文保存的更改是否保证在第二个上下文的范围内可见?
var txOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions))
{
using (var context1 = new MyDbContext())
{
context1.Employees.Single(e => e.Id == 1).Salary += 1; // Update
context1.Employees.Remove(context1.Employees.Single(e => e.Id == 2)); // Delete
context1.Employees.Add(new Employee { Id = 3 }); // Add
context1.SaveChanges();
}
using (var context2 = new MyDbContext())
{
// are changes saved by context1 guaranteed to be visible here?
}
transaction.Complete();
}
通常我会希望他们是,但后来我看到“No, this was a coincidence because the 2nd context reused the connection of the 1st from the connection pool. This is not guaranteed and will break under load.”让我感到困惑。任何人都可以确认或反驳这一点吗?
【问题讨论】:
标签: c# entity-framework dbcontext transactionscope