In Entity Framework 4.0 “Nested transactions are not supported” error is displayed?

旧街凉风 提交于 2019-12-13 14:15:54

问题


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

回答1:


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



回答2:


you are adding two objects at a time in a same function so you get error table1 object data and table 2 object data add in different block.



来源:https://stackoverflow.com/questions/16849954/in-entity-framework-4-0-nested-transactions-are-not-supported-error-is-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!