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

在提供程序连接上启动事务时发生错误。 有关详细信息,请参阅内部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个不同连接引起的。 您应该手动控制连接:

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

您在同一个函数中一次添加两个对象,因此您可以在不同的块中获取错误table1对象数据和表2对象数据。