2015-11-06 105 views
0

我在學習Linq2SQL,並且在左外連接上有一個問題。 在我下面的示例中,我相信我正在將問題表上的左外連接執行到favoritequestions表。但我不相信我的where子句是正確的。 因此,如果我在兩個表上執行一個左出連接,我應該如何適當地設置where子句?Linq To SQL加入

var myResults = from quest in context.MyQuestions 
       join favQuest in context.MyFavoriteQuestions on quest.UserFavoriteQuestionId equals favQuest.UserFavoriteQuestionId 
       join specialQuest in context.Questions on favQuest.QuestionId equals specialQuest.QuestionId into joinedQuestions 
       from specialQuest in joinedQuestions.DefaultIfEmpty() 
       where (quest.UserId == userId) && 
            (specialQuest.Id == paramId && (!specialQuest.IsBlue || (specialQuest.IsBlue && canViewBlueQuestion)) && 
             (!specialQuest.IsRed || (specialQuest.IsRed && canViewRedQuestion)) 
            ) 
           select quest; 
+1

LinqToSql已被實體框架所取代......你應該看看使用來代替。 – Belogix

+0

對於您不需要EF帶來的膨脹的項目,LINQ2SQL沒什麼問題。 – lsedlacek

+0

@Belogix - 你建議改變一個工具,運行速度會變慢,不能提供很大的彈性 – Hogan

回答

1

對於LINQ到SQL上下文,建議寫左外連接同樣地,作爲實際上產生一個SQL LEFT JOIN:

var myResults = from question in context.MyQuestions 
from favoriteQuestion in context.MyFavoriteQuestions 
    .Where(fc => fc.UserFavoriteQuestionId == question.UserFavoriteQuestionId) 
    .DefaultIfEmpty() 

還建議(提高易讀性),以獨立無關的(和AND ED)where子句:

var myResults = from question in context.MyQuestions 
       where question.UserId == userId 
       from favoriteQuestion in context.MyFavoriteQuestions 
        .Where(fc => fc.UserFavoriteQuestionId == question.UserFavoriteQuestionId) 
        .DefaultIfEmpty() 
       from specialQuestion in context.Questions 
        .Where(sc => sc.QuestionId == favoriteQuestion.QuestionId) 
        .DefaultIfEmpty() 
       where specialQuestion.Id == paramId 
       where !specialQuestion.IsBlue || (specialQuestion.IsBlue && canViewBlueQuestion) 
       where !specialQuestion.IsRed || (specialQuestion.IsRed && canViewRedQuestion) 
       select question; 
+0

謝謝,這將有助於瞭解如何構建更好的查詢。 – PrivateJoker