Find parent based on children properties linq to sql
开发者_C百科Lets say we have a sql relationship that can be modeled like this using C# classes
public class Parent
{
public int ID { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int ID { get; set; }
public Parent Parent { get; set; }
public int Number { get; set; }
}
I also know that the parent only has two children. I would I find all the parents where the children both satisfy a different criteria? Say One Child has a number = 0 and the other Child has a number = 1
Goin' out on a limb here...
(from p in context.Parents
where p.Children.Count == 2
where p.Children.Any(c => c.Number == 0)
select p).Where(p => p.Children.Any(c => c.Number == 1));
from p in context.Parents
where p.Children.Count == 2 // sounds like you can skip this one
where p.Children.Any(c => c.Number == 0)
where p.Children.Any(c => c.Number == 1)
select p;
from o in context.Parents where o.Children.Count == 2 && o.Children.Any(x => x.Number == 0) && x.Children.Any(x => x.Number == 1) select o;
精彩评论