问题
Given a list of parents and their children I want to return a list of all parents and only their male children. This is trivial in a sql query. The problem I have is with Linq to EF I cannot seem to get the query to work in any fashion. Due to EF limitations I cannot do an include to ensure the return of the Children I want. How do I accomplish the below sql in LINQ to return my Parent Entity with Children Collection with only males or Empty collections ignoring all of the female records?
SQL
SELECT p.Id, p.FirstName, p.LastName, c.Id, c.ParentId, c.FirstName, c.LastName, c.Sex FROM Parent p
LEFT JOIN children c ON c.ParentId = p.Id AND c.Sex = 'M'
回答1:
You can accomplish this if you don't mind projecting to an anonymous type or POCO like so:
Parent with a collection of children:
var query = from p in context.Parents
join c in context.Children.Where(x => x.Sex == 'M') on p.Id equals c.ParentId into childrenGroup
select new
{
Parent = p,
Children = childrenGroup,
};
Flattened list:
var query = from p in context.Parents
from c in context.Children.Where(x => p.Id == x.ParentId)
.Where(x => x.Sex == 'M')
.DefaultIfEmpty()
select new
{
ParentId = p.Id,
ParentFirstName = p.FirstName,
ParentLastName = p.LastName,
ChildId = c.Id,
ChildFirstName = c.FirstName,
ChildLastName = c.LastName,
ChildSex = c.Sex
};
回答2:
try the Where Not In operator
var query =
from p in dc.Parent
where !(from c in dc.children
select c.ParentId where c.Sex = 'F')
.Contains(c.ParentId)
select c;
I don't know your object structure so you'll have to tweak the query but the basic concept should get you to where you want to be. (I make no claims that the syntax is exactly correct :-p)
来源:https://stackoverflow.com/questions/9705463/linq-to-entity-framework-return-a-list-of-parents-with-only-a-subset-or-empty-co