在Entity Framework 4.0中“不支持嵌套事务”;提示错误

本文关键字:嵌套事务 提示 错误 不支持 Framework Entity | 更新日期: 2023-09-27 18:16:06

在提供者连接上启动事务时发生错误。有关详细信息,请参阅内部异常。"不支持嵌套事务。"内部异常

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();
                }
           }
}

在Entity Framework 4.0中“不支持嵌套事务”;提示错误

可能是由于事务中使用了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();
}

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