I am pretty green with LINQ and brand new to converting LEFT JOINs. I wrote a query in SQL (which works fine) and I am trying to get it into LINQ. I am missing something, but can't see it. The SQL is:
DECLARE @Version int = 1
SELECT Q.WebFormTemplateQuestionID, Lay.*
FROM WebFormTemplates WFT
INNER JOIN WebFormTemplateQuestions Q ON Q.WebFormTemplateID = WFT.WebFormTemplateID
LEFT JOIN WebFormTemplateLayoutHeaders Hdr ON Hdr.WebFormTemplateID = WFT.WebFormTemplateID and hdr.Version = @Version
LEFT JOIN WebFormTemplateLayouts Lay ON Lay.WebFormTemplateLayoutHeaderID = Hdr.WebFormTemplateLayoutHeaderID AND Lay.WebFormTemplateQuestionID = Q.WebFormTemplateQuestionID
WHERE WFT.WebFormTemplateID = 2
ORDER BY Q.SortOrder
The LINQ I wrote is:
Version = 1
Dim q3 = From WFT In ctx.WebFormTemplates
Join Q In ctx.WebFormTemplateQuestions On Q.WebFormTemplateID Equals WFT.WebFormTemplateID
Group Join Hdr In ctx.WebFormTemplateLayoutHeaders On Hdr.WebFormTemplateID Equals WFT.WebFormTemplateID Into Hdr_join = Group
From Hdr In Hdr_join.Where(Function(x) x.Version = Version).DefaultIfEmpty()
Group Join Lay In ctx.WebFormTemplateLayouts On Lay.WebFormTemplateLayoutHeaderID Equals Hdr.WebFormTemplateLayoutHeaderID And Lay.WebFormTemplateQuestionID Equals Q.WebFormTemplateQuestionID Into Lay_join = Group
From Lay In Lay_join.DefaultIfEmpty()
Where WFT.WebFormTemplateID = 2
With this, I can break the code and in the immediate window get the expected values when I type:
?q3.FirstOrDefault().Hdr.Version
But for the Lay item I need to type:
?q3.FirstOrDefault().Lay.FirstOrDefault().QuestionAlign
to get the value. Why do I need to call FirstOrDefault the second time? What am I missing here? When I do a Select, the values are all null for Lay I assume because I don't have another FirstOrDefault someplace. Everything from Hdr, WFT, and Q work just fine. Can anyone explain what is going on?