实体框架事务未回滚

本文关键字:事务 框架 实体 | 更新日期: 2023-09-27 18:08:39

下面的代码在一个循环中执行多次。当我执行下面的代码时,它偶尔会生成一个外键异常,这很好,因为它被处理了,我尝试回调事务的角色。但是,在下一次运行时,它会生成相同的异常,并且即使数据是正确的,它也会一次又一次地生成相同的异常。

我们有一个存储上下文的单例类:

public class MyDatabaseContext
    {
        private static MyDatabaseContext _instance;
        public static MyDatabaseContext_Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new MyDatabaseContext();
                }
                return _instance;
            }
        }
        public MyEntities Context;

        private MyDatabaseContext()
        {
            Context = new MyEntities();
        }
    }
}

循环主要部分的缩减版本:

MyEntities entities = MyDatabaseContext.Instance.Context;
// Begin new transaction
entities.Connection.Open();
DbTransaction transaction = entities.Connection.BeginTransaction();
try {
    // Inside the update, we modify some data and call saveChanges() on the same
    // database context, see below
    dataObject.Update()
    // do more stuff to data here
    if (dataObject.isValid())
    {
        transaction.Commit();
    }
} catch (Exception ex) {
    // Rollback transaction
    transaction.Rollback();
} fincally {
    entities.Connection.Close();
}

这是Update()方法,它会导致异常

public static Update() {
    // get same database context
    MyEntities entities = MyDatabaseContext.Instance.Context;
    // Update data, wont show here, but a foreign key is set to 0 which 
    //will cause an exception
    entities.saveChanges() // Exception thrown here! 
}

实体框架事务未回滚

MS SQL不支持嵌套事务。很可能您已经在事务中了,所以Begin/Commit/Rollback是逻辑事务,而不是物理事务。

尝试使用SQL Profiler检查它,看看实际发生了什么。

简单的(但不是最好的)解决方案是,任何时候你做Rollback,你实际上需要关闭连接,重新开始。