LINQ Query - Complicated Self Join Problems
So I have Projects (for t开发者_JS百科his example say they are a Name and an ID). I also have a table called SubProjects, like this:
MasterProjectID SubProjectID 1 2 1 3 4 5 4 6 4 7
A master cannot be a sub of another master.
I want to return a list of project IDs. Specifically, I want the list to contain the Master project ID and all of its Sub project IDs.
In other words, if projectID == 4 and pdc is my DataContext, my query should return:
4 5 6 7
The following linq query returns nothing:
from j in pdc.Projects
join s in pdc.SubProjects on j.ProjectID equals s.SubProjectID
where j.ProjectID.Equals(projectID) || s.MasterProjectID.Equals(projectID)
select j.ProjectID;
What am I doing wrong?
You could retrieve a list of sub-projects simply with:
var query = from j in pdc.SubProjects
where j.MasterProjectID == projectID
select j.SubProjectID;
... Then manually append/prepend the known value of projectID
.
var list = query.ToList();
list.Add(projectID);
精彩评论