3

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

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

2 回答 2

4

这可能是由事务中使用的 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();
}
于 2013-05-31T06:33:13.473 回答
1

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

于 2013-05-31T05:08:36.750 回答