【发布时间】:2015-08-25 08:39:28
【问题描述】:
当 Entity Framework 操作中发生错误时,任何环境事务都会中止,我无法将其用于更多数据库工作。例如,一旦我尝试打开嵌套事务范围,它就会抛出 TransactionAbortedException 说“事务已中止”。
当我预计会出现错误并知道如何继续时,我可以做些什么来防止这种情况发生?
using (var scope = new TransactionScope())
{
using (var ctx = new MyContext())
{
try
{
var x = ctx.MyEntities.FirstOrDefault();
}
catch
{
CreateTable();
// Custom DDL command. I can't use EF migrations.
// Should that fail or not help, I'm happy to see more exceptions later.
}
// TODO: Transaction scope is already aborted!
ctx.MyEntities.Add(...);
}
scope.Complete();
}
如果有帮助,我可以创建一个新的 DbContext 实例。
【问题讨论】:
标签: .net entity-framework transactions