【问题标题】:In Entity Framework 4.0 "Nested transactions are not supported" error is displayed?在 Entity Framework 4.0 中显示“不支持嵌套事务”错误?
【发布时间】:2013-05-31 16:39:21
【问题描述】:

在提供程序连接上启动事务时出错。有关详细信息,请参阅内部异常。 “不支持嵌套事务。” 内部异常

public bool Insert(myModel model)
{
            entities.Database.Connection.Open();
            using (DbTransaction trans = entities.Database.Connection.BeginTransaction())
            {
                try
                {
                    table1 obj1 = new table1
                    {
                        AccountHolderName = model.AccountHolderName,
                        AccountNumber = model.AccountNumber,
                        Address = model.Address,
                    };
                    entities.table1.Add(obj1);
                    entities.SaveChanges();

                    long id = obj1.ID;

                    table2 obj = new table2
                    {
                        ID = model.ID == 1 ? id : model.ID,
                        Username = model.Email,
                        Password = model.Password,
                    };
                    entities.table2.Add(obj2);
                    entities.SaveChanges();
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                }
                finally
                {
                    entities.Database.Connection.Close();
                }
           }
}

【问题讨论】:

    标签: c# mysql entity-framework-4 entity


    【解决方案1】:

    这可能是由事务中使用的 2 个不同的连接引起的。您应该手动控制连接:

    objectContext = ((IObjectContextAdapter)entities).ObjectContext;
    try{
        objectContext.Connection.Open();
        using (var tran = new TransactionScope()) {
            table1 obj1 = new table1
            {
                AccountHolderName = model.AccountHolderName,
                AccountNumber = model.AccountNumber,
                Address = model.Address,
            };
            entities.table1.Add(obj1);
            entities.SaveChanges();
    
            table2 obj = new table2
            {
                ID = model.ID == 1 ? id : model.ID,
                Username = model.Email,
                Password = model.Password,
            };
            entities.table2.Add(obj2);
            entities.SaveChanges();
    
            tran.Complete();
        }
    }
    finally{
        objectContext.Connection.Close();
    }
    

    【讨论】:

      【解决方案2】:

      您在同一个函数中一次添加两个对象,因此您会得到错误表 1 对象数据和表 2 对象数据添加到不同的块中。

      【讨论】:

      • 感谢您的帮助...我试过了,但没有用。任何建议。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多