【发布时间】:2012-05-30 08:52:12
【问题描述】:
我在使用带有实体框架的 Sql Server CE 4 和 System.Transactions.TransactionScope 抑制部分事务时遇到问题。
下面的简化代码来自演示问题的单元测试。
这个想法是使innerScope 块(没有事务)成功或失败而不影响outerScope 块(“环境”事务)。这是TransactionScopeOption.Suppress 的既定目的。
但是,代码失败,因为似乎整个SomeTable 表被outerScope 中的第一个插入锁定。在代码中指示的位置,抛出此错误:
“SQL Server Compact 等待锁定超时。设备的默认锁定时间为 2000 毫秒,桌面为 5000 毫秒。可以使用 ssce: default lock timeout 属性在连接字符串中增加默认锁定超时。[ 会话 id = 2,Thread id = 2248,Process id = 13516,Table name = SomeTable,Conflict type = x lock (x blocks),Resource = PAG (idx): 1046 ]"
[TestMethod()]
[DeploymentItem("MyLocalDb.sdf")]
public void MyLocalDb_TransactionSuppressed()
{
int count = 0;
// This is the ambient transaction
using (TransactionScope outerScope = new TransactionScope(TransactionScopeOption.Required))
{
using (MyObjectContext outerContext = new MyObjectContext())
{
// Do something in the outer scope
outerContext.Connection.Open();
outerContext.AddToSomeTable(CreateSomeTableRow());
outerContext.SaveChanges();
try
{
// Ambient transaction is suppressed for the inner scope of SQLCE operations
using (TransactionScope innerScope = new TransactionScope(TransactionScopeOption.Suppress))
{
using (MyObjectContext innerContext = new MyObjectContext())
{
innerContext.Connection.Open();
// This insert will work
innerContext.AddToSomeTable(CreateSomeTableRow());
innerContext.SaveChanges(); // ====> EXCEPTION THROWN HERE
// There will be other, possibly failing operations here
}
innerScope.Complete();
}
}
catch { }
}
outerScope.Complete();
}
count = GetCountFromSomeTable();
// The insert in the outer scope should succeed, and the one from the inner scope
Assert.AreEqual(2, count);
}
因此,根据http://msdn.microsoft.com/en-us/library/ms172001,似乎“事务范围内的事务在隔离级别设置为 Serializable 的情况下执行”
但是,使用下面的代码 sn -p 来改变 TransactionScope 的隔离级别并没有帮助:
public void MyLocalDb_TransactionSuppressed()
{
TransactionOptions opts = new TransactionOptions();
opts.IsolationLevel = IsolationLevel.ReadCommitted;
int count = 0;
// This is the ambient transaction
using (TransactionScope outerScope = new TransactionScope(TransactionScopeOption.Required, opts))
...
在相同的位置抛出相同的异常。
似乎避免这种情况的唯一方法是在进入innerScope 块之前调用outerScope.Complete()。但这会破坏目的。
我在这里缺少什么? 谢谢。
【问题讨论】:
标签: c# .net entity-framework sql-server-ce system.transactions