c# - 在 Entity Framework 4.0 中显示 "Nested transactions are not supported"错误?

标签 c# mysql entity-framework-4 entity

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

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 个不同的连接引起的。您应该手动控制连接:

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

关于c# - 在 Entity Framework 4.0 中显示 "Nested transactions are not supported"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16849954/

相关文章:

C# 隐藏和取消隐藏评论

c# - 根据特定字母从字符串中获取字母链

c# - 解析复杂 json 字符串的最佳实践

C# 4.0/EF - SQL Server Compact 不支持服务器生成的键和服务器生成的值

c# - "Or"Together Expression<Func<EntityFramework Entity, bool>> in .NET 4, Silverlight RIA 域服务

c# - Web API IValueProvider 接口(interface)的 ContainsPrefix 方法的用途是什么?

javascript - 生成 PHP 数组以模仿 JSON 格式

php - 如何找出sql表中缺失的数字

mysql - 添加 WHERE 子句后对连接结果感到困惑

entity-framework - Visual Studio 2010 中的 EntityConfiguration 和 ContextBuilder 在哪里?