根据子属性linq to sql查找父级

时间:2010-08-26 04:28:06

标签: c# sql linq linq-to-sql

假设我们有一个可以使用C#类

建模的SQL关系
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; } 
} 

我也知道父母只有两个孩子。我会找到孩子们满足不同标准的所有父母吗? Say One Child的数字= 0,另一个Child的数字= 1

3 个答案:

答案 0 :(得分:2)

在这里走出困境......

(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));

答案 1 :(得分: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;

答案 2 :(得分:0)

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;