2015-11-06 88 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