2013-05-31 33 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