2013-05-31 59 views
3

在提供程序連接上啓動事務時發生錯誤。詳情請參閱內部例外。 「嵌套事務不受支持。」 內部異常在實體框架4.0中顯示「不支持嵌套事務」錯誤?

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個不同連接引起的。你應該手動控制連接:

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

酷解決了我的問題.... thnx – faraaz

1

你在一個時間在同一功能附加兩個物體這樣就可以獲得錯誤table1的對象數據和表2對象數據添加在不同的塊中。

+0

讚賞你的幫助...我試過了,而且沒有工作。有什麼建議麼。 – faraaz