2015-04-20 67 views
0

我試圖在TransactionScope裏面插入父子關係的數據,並且我得到了INSERT statement conflicted with the FOREIGN KEY constraint錯誤。這裏是我的代碼:TransactionScope中的父子插入導致外鍵約束錯誤

using (var scope = new TransactionScope()) 
{ 
    try 
    { 
     discount = discountDataAccess.Insert(discount); 
     switch (discount.Type) 
     { 
      case eDiscountType.PerCustomer: 
       InsertDiscountCustomer(discount.Id, idList); 
       break; 

      case eDiscountType.PerPackage: 
       InsertDiscountPackage(discount.Id, idList); 
       break; 
     } 

     scope.Complete(); 
     return discount; 
    } 
    catch (Exception ex) 
    { 
     scope.Dispose(); 
     throw; 
    } 
} 

DiscountCustomerDiscountPackage將被插入,Discount.Id仍然是0因爲沒有插入到數據庫中,直到scope.Complete()數據調用。所以基本上我不能保存DiscountCustomerDiscountPackage,直到我提交DiscountTransaction直到兩個都保存成功爲止未提交。

有沒有什麼辦法可以在TransactionScope裏插入父母和子女?

回答

2

我發現分佈式事務是不可能的,因爲TransactionScope仍然在方法的上下文中,直到調用scope.Complete()纔會插入任何內容。但它可以通過SqlTransaction類來完成,該類可以從SqlConnection中檢索。

try 
{ 
    var transaction = connection.BeginTransaction(); 
    discount = discountDataAccess.Insert(discount, transaction); 
    switch (discount.Type) 
    { 
     case eDiscountType.PerCustomer: 
      InsertDiscountCustomer(discount.Id, idList, transaction); 
      break; 

     case eDiscountType.PerPackage: 
      InsertDiscountPackage(discount.Id, idList, transaction); 
      break; 
    } 

    transaction.Commit(); 
    return discount; 
} 
catch (Exception ex) 
{ 
    if (transaction != null) 
     transaction.Rollback(); 

    throw; 
}