Entity Framework: TransactionScope 具有不同的 IsolationLevel
Entity Framework: TransactionScope has a different IsolationLevel
我正在尝试在域级别使用 TransactionScope
,因此我可以跨(可能)多个存储库操作数据,但将所有这些保存在同一事务中。
我有以下保存方法:
public void Save(MyEntity source)
{
using (var scope = new TransactionScope())
{
var context = new MyEFEntities(environment.ConnectionString);
this.Repository.Add(source.ToDbMyEntity(), context);
context.SaveChanges();
scope.Complete();
}
}
但我在 .SaveChanges()
上收到以下错误:
The transaction specified for TransactionScope has a different
IsolationLevel than the value requested for the scope. Parameter name:
transactionOptions.IsolationLevel
这是什么原因造成的?
我认为 Entity framework 的默认隔离级别是数据库的默认隔离级别,例如 SqlServer 的默认隔离级别是 READ COMMITTED
,而 TransactionScope 默认是 Serializable
因此,当您尝试在 using (var scope = new TransactionScope())
块内更改它时,它会引发错误。尝试这样的事情:
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions));
我正在尝试在域级别使用 TransactionScope
,因此我可以跨(可能)多个存储库操作数据,但将所有这些保存在同一事务中。
我有以下保存方法:
public void Save(MyEntity source)
{
using (var scope = new TransactionScope())
{
var context = new MyEFEntities(environment.ConnectionString);
this.Repository.Add(source.ToDbMyEntity(), context);
context.SaveChanges();
scope.Complete();
}
}
但我在 .SaveChanges()
上收到以下错误:
The transaction specified for TransactionScope has a different IsolationLevel than the value requested for the scope. Parameter name: transactionOptions.IsolationLevel
这是什么原因造成的?
我认为 Entity framework 的默认隔离级别是数据库的默认隔离级别,例如 SqlServer 的默认隔离级别是 READ COMMITTED
,而 TransactionScope 默认是 Serializable
因此,当您尝试在 using (var scope = new TransactionScope())
块内更改它时,它会引发错误。尝试这样的事情:
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions));