2009-05-06 55 views
1

我有一個問題表,它連接到一個解決方案表。解決方案與問題相關,但爲了刪除問題,我必須先刪除該問題的解決方案,然後刪除問題本身。Linq刪除加入

我有一個linq查詢檢索特定問題的所有解決方案,但我不知道如何繼續刪除解決方案,然後繼續刪除問題。

下面是代碼,它臨危超載的錯誤消息:

public static void DeleteSol(string qTextInput) 
{ 
    ExamineDataContext dc = new ExamineDataContext(); 
    var matchedSol = from q in dc.Questions 
          where q.QuestionText.Contains(qTextInput) 
          join s in dc.Solutions 
          on q.QuestionID equals s.QuestionID 
          into qs // note grouping   
          select new 
          { 
           solution = qs 
          }; 
    try 
    { 
     dc.Solutions.DeleteOnSubmit(matchedSol); 
     dc.SubmitChanges(); 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
} 

回答

3

如果您有您的問題和解決方案之間的外鍵關係,只需設置它,以便刪除傳播(CASCADE ON DELETE)。這樣你只需要刪除問題,解決方案就會被數據庫自動刪除。

使用外鍵關係也會給你一個在你的Question實體上設置的實體,它將直接加載相關的Solution實體並使之成爲可以避免一直寫入連接邏輯。在添加設計器的外鍵關係後,您需要刪除並重新添加實體 - 或者您可以在設計器中手動輸入add the association

1

我覺得用加入是問題的根源。嘗試創建問題和Soutions之間的DBML的映射,那麼你就可以簡單地寫:

var questions = from q in Questions where q.QuestionText.Contains(qTextInput); 
var solutions = questions.SelectMany(q => q.Solutions); 
... 
dc.Solutions.DeleteAllOnSubmit(solutions); 
0

問題是matchedSol不是IEnumerable<Solution>類型。如果您的代碼編譯完成,我會感到驚訝。

你需要的是這個(示例使用LINQ2Objects但這並不有所作爲):

static void Main() 
{ 
    var questions = new[] 
         { 
          new { QuestionID = 1, QuestionText = "ABCDEF" }, 
          new { QuestionID = 2, QuestionText = "GHIJKL" }, 
          new { QuestionID = 3, QuestionText = "ABCXYZ" }, 
         }; 
    var solutions = new[] 
         { 
          new { QuestionID = 1, Solution = "P" }, 
          new { QuestionID = 1, Solution = "Q" }, 
          new { QuestionID = 2, Solution = "R" }, 
          new { QuestionID = 3, Solution = "S" }, 
          new { QuestionID = 3, Solution = "T" }, 
          new { QuestionID = 4, Solution = "U" }, 
         }; 
    var qTextInput = "ABC"; 
    var matchedSol = from q in questions 
        where q.QuestionText.Contains(qTextInput) 
        join s in solutions 
        on q.QuestionID equals s.QuestionID 
        select s; 

    foreach (var solution in matchedSol) 
    { 
     Console.WriteLine("Solution " + solution.Solution + 
          " for question " + solution.QuestionID); 
    } 
} 

的LINQ表達式的結果是一個枚舉的四個解決方案:PQST。這個枚舉可以給你的方法DeleteOnSubmit

+0

恐怕沒有工作...... – Goober 2009-05-06 17:27:34