2010-04-26 41 views
0

我有兩個表Table1與列[BId,名稱,數量]表2與列[CId,BId,費用類型,費用]。 BId是表2中的外鍵。更新LINQ中的一個查詢中的2個表值

Table1中的Amount字段總是高於Table2中的Expense。我需要根據Expense的值更新Amount(增加或減少)的值,並且我想在LINQ中的單個查詢中執行它。例如,如果費用必須用200更新,則會減少(否定)200的金額。如果費用減少到100,則金額增加100。

在此先感謝您的任何建議。

回答

1

您無法使用一個查詢執行更新。你甚至不能在SQL中這樣做,更不用說在LinQ中。你需要的是一項交易。 在事務中,您可以將兩個表記錄加載到變量中,更新它們的值並提交事務。

using (var transaction = new TransactionScope()) { 
    try { 
     record1 = (from r in myDataContext.Table1s where r.BId == myBid select r).FirstOrDefault(); 
     record2 = (from r in myDataContext.Table2s where r.BId == myBid select r).FirstOrDefault(); 

     // Perform your record updates here 
     var oldExpense = record2.Expense; 
     record2.Expense = newExpense; 
     record1.Amount += (newExpense - oldExpense); 

     myDataContext.SubmitChanges(); // if an exception occurs here, the transaction is aborted 

     transaction.Complete(); // commits the transaction 

    } catch (Exception ex) { 
     // TODO: Exception handling 
    } 
} 
+0

非常感謝你,正是我所需要的 – fireBand 2010-04-26 18:51:56

相關問題