John Doe
John Doe

Reputation: 3243

Linq To SQL Join

I am learning Linq2SQL and I have a question on the left outer join. In my example below I believe that I am performing the left outer join on the questions table to the favoritequestions table. However I don't believe that my where clause is correct. So if I perform a left out join on two tables how should I set up the where clause appropriately?

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;

Upvotes: 0

Views: 55

Answers (1)

lsedlacek
lsedlacek

Reputation: 323

For LINQ to SQL contexts it is suggested to write the left outer join as such, as that actually generates a SQL LEFT JOIN:

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

It is also suggested (to improve legibility) to separate unrelated (and ANDed) where clauses:

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;

Upvotes: 1

Related Questions