c# – 使用TransactionScopeOption.Suppress与Sql Server Compac
我在使用带有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().但这会破坏目的. 我在这里错过了什么? 解决方法
AFAIK SQL Server Compact不支持嵌套事务.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |