这是一个使用 SQL Server CE 3.5 SP1 的非常简单的示例,我尝试在现有事务中使用新事务。
using (var db = new MyDataContext(<connection string>))
using (var ts = new TransactionScope())
{
db.Thing.InsertOnSubmit(new Thing());
db.SubmitChanges();
using (var ts2 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
db.Thing.InsertOnSubmit(new Thing());
db.SubmitChanges(); // exception here
ts2.Complete();
}
[... do more stuff ...]
ts.Complete();
}
这会导致错误“连接对象无法在事务范围内登记”。第二次调用“db.SubmitChanges()”
这篇文章指出 SQL CE 不支持一个事务内的两个连接,但我这里只有一个(除非 SubmitChanges() 创建另一个连接)。
上面的想法是,如果子事务提交,那么即使外部事务失败,它也会保持提交状态。据我所知,这是 RequiresNew 的预期用途。
这篇 MSDN 文章 声称 SQL CE 支持嵌套事务本身,因此我认为上述应该是可能的。是吗?如果是这样,我该如何修改代码才能使其工作?
编辑:虽然这篇 MSDN 文章与另一篇 MSDN 文章表示不支持嵌套事务。也许这就是问题所在?
Here's a very simple example using SQL Server CE 3.5 SP1 where I attempt to use a new transaction inside an existing one.
using (var db = new MyDataContext(<connection string>))
using (var ts = new TransactionScope())
{
db.Thing.InsertOnSubmit(new Thing());
db.SubmitChanges();
using (var ts2 = new TransactionScope(TransactionScopeOption.RequiresNew))
{
db.Thing.InsertOnSubmit(new Thing());
db.SubmitChanges(); // exception here
ts2.Complete();
}
[... do more stuff ...]
ts.Complete();
}
This causes the error "The connection object can not be enlisted in transaction scope." on the second call to "db.SubmitChanges()"
This article states that SQL CE does not support two connections inside one transaction, but I only have one here (unless SubmitChanges() creates another one).
The idea above is that if the sub-transaction commits then it stays committed even if the outer transaction fails. To the best of my understanding, this is the intended use of RequiresNew.
This MSDN article claims that SQL CE supports nested transactions as such, hence my thinking that the above should be possible. Is it? If so, how do I modify the code to make this work?
Edit: While this MSDN article contradicts the other MSDN article and says nested transactions are not supported. Perhaps that is the problem?
发布评论
评论(3)
不可以,您不能使用嵌套事务。在 SQL CE 数据库上运行此代码,您将看到错误消息。
主要错误 0x80004005,次要错误 27994
Microsoft SQL Server Compact 不支持嵌套事务。
Nope, you cannot use nested transactions. Run this code on your SQL CE database and you will see the error message.
Major Error 0x80004005, Minor Error 27994
Microsoft SQL Server Compact does not support nested transactions.
就您而言,您不应该使用 TransactionScope。
您必须调用 DataContext.Transaction = DataContext.Connection.BeginTransaction 并控制您自己的事务。
In your case, you should not use TransactionScope.
You will have to call DataContext.Transaction = DataContext.Connection.BeginTransaction and control your own transaction.
可能的解决方案: http://fknet .wordpress.com/2011/02/25/entity-framework-problemsolution-of-default-connection-fitting/
Possible solution: http://fknet.wordpress.com/2011/02/25/entity-framework-problemsolution-of-default-connection-closing/