【问题标题】:Entity Framework Transaction not rolling back实体框架事务不回滚
【发布时间】:2013-04-11 23:41:02
【问题描述】:

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

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

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! 
}

【问题讨论】:

    标签: c# .net database entity-framework transactions


    【解决方案1】:

    MS SQL 不支持嵌套事务。很可能您已经在事务中,所以 Begin / Commit / Rollback 是 logical 事务而不是 physical 数据库事务。

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

    简单(但当然不是最好的)解决方案是,无论何时您执行Rollback,您实际上都需要关闭连接并重新开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多