I have the following in SQL:
SELECT * FROM (SELECT Teikoku_Sections.Section_ID, Teikoku_Sections.Section_Name, Teikoku_Sections.Section_Code, Teikoku_Sections.Show_In_Menu FROM Teikoku_Sections WHERE Teikoku_Sections.Show_In_Menu = 1) AS Sections
LEFT OUTER JOIN (SELECT Teikoku_Divisions.Division_ID, Teikoku_Divisions.Division_Name, Teikoku_Divisions.Division_Code, Teikoku_Divisions.Section_ID, Teikoku_Divisions.Show_In_Menu FROM Teikoku_Divisions WHERE Teikoku_Divisions.Show_In_Menu = 1) AS Divisions
ON Sections.Section_ID = Divisions.Section_ID;
Which performs a left outer join on the two tables Teikoku_Sections and Teikoku_Divisions and join the visible items from both tables together.
The tables have the structure:
Teikoku_Section:
Section_ID int,
Section_Name nvarchar(50),
Section_Code int,
Show_In_Menu bit
Teikoku_Divisions:
Division_ID int,
Division_Name nvarchar(50)
Division_Code int,
Section_ID int, <== The ID of the parent section
Show_In_Menu bit
I would like to end up with a table showing all sections and divisions which have Show_In_Menu true, but in some cases there might not be any divisions corresponding to a section, hence the LEFT OUTER JOIN.
I just can’t get my head round to how to do this in linq to sql.
So far I have:
//Get All Visible sections
IQueryable<Teikoku_Section> visibleSections = from section in db.Teikoku_Sections where section.Show_In_Menu select section;
//Get all visible divisions
IQueryable<Teikoku_Division> visibleDivisions = from division in db.Teikoku_Divisions where division.Show_In_Menu select division;
//Join the two together
IQueryable menuItems = visibleSections.GroupJoin(visibleDivisions, section => section.Section_ID,
division => division.Section_ID, (section, divisions) => new
{
Section_ID = section.Section_ID,
Section_Name = section.Section_Name,
Division_ID = divisions.Select(d => d.Division_ID),
Division_Name = divisions.Select(d => d.Division_Name),
});
return menuItems;
Which doesn’t quite work… I think I might be missing a SelectMany(), but I just can’t figure where or how to put it.
Look into DefaultIfEmpty (http://msdn.microsoft.com/en-us/library/bb355419.aspx)