在实体框架4.0中“不支持嵌套事务”显示错误? [英] In Entity Framework 4.0 "Nested transactions are not supported" error is displayed?

查看:216
本文介绍了在实体框架4.0中“不支持嵌套事务”显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提供商连接上启动事务时发生错误。查看内部例外情况。 不支持嵌套事务。
内部异常

An error occurred while starting a transaction on the provider connection. See the inner exception for details. "Nested transactions are not supported." Inner Exception

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


推荐答案

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

It is probably caused by 2 different connections used in transaction. You should control connection manually:

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

这篇关于在实体框架4.0中“不支持嵌套事务”显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆