我在使用带有Entity Framework和System.Transactions.TransactionScope的sql Server CE 4来抑制部分事务时遇到了问题.
下面的简化代码来自演示问题的单元测试.
我们的想法是在不影响outerScope块(“环境”事务)的情况下启用innerScope块(没有事务)成功或失败.这是TransactionScopeOption.Suppress的既定目的.
但是,代码失败,因为似乎整个SoMetable表被outerScope中的第一个插入锁定.在代码中指示的位置,抛出此错误:
“sql Server Compact等待锁定超时.设备的默认锁定时间为2000ms,桌面的默认锁定时间为5000ms.使用ssce:default lock timeout属性可以在连接字符串中增加默认锁定超时.[Session id = 2,线程id = 2248,进程id = 13516,表名= SoMetable,冲突类型= x锁(x块),资源= 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”
但是,使用以下代码段更改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().但这会破坏目的.
我在这里错过了什么?
谢谢.
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。