如何在LINQ to SQL查询中排除特定的关联记录?

时间:2015-06-04 20:37:33

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

假设我有以下数据:

Parent
  > Child 1 (Alive = true)
  > Child 2 (Alive = true)
    > Grandchild 1 (Alive = false)
    > Grandchild 2 (Alive = true)
  > Child 3 (Alive = false)
    > Grandchild 3 (Alive = false)

我想编写一个查询来选择Alive为true的所有记录,从而排除Alive为false的任何内容。这是我想弄清楚的语法:

from p
in this.People
where p.IsAlive && (p.Children.IsAlive)  && (p.Children.Children.IsAlive)
select p

我希望结果集看起来像这样:

Parent
  > Child 1 (Alive = true)
  > Child 2 (Alive = true)
    > Grandchild 2 (Alive = true)

1 个答案:

答案 0 :(得分:0)

你可以这样做: 1)通过ParentID列创建具有递归关系的表:

repeat
  IdHttp.Get(sURL+WebFile[I], S, [404]);
  if IdHttp.ResponseCode <> 404 then
    Break;
  Inc(I);
until False;

2)对Alive记录执行如下所示的查询:

Table name : People
ID  Name        ParentID IsAlive
1   Parent1     Null       1
2   Child1      1          1
3   Child2      1          1
4   GrandChild1 3          1
5   GrandChild2 3          0
6   Child3      1          0
7   GrandChild3 6          0

请让我知道,这种方式适合你吗?