简体   繁体   English

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

[英]How can I exclude specific association records in a LINQ to SQL query?

Assume I have the following data: 假设我有以下数据:

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)

And I want to write a query to select all the records where Alive is true, thereby excluding anything where Alive is false. 我想编写一个查询以选择Alive为true的所有记录,从而排除Alive为false的所有记录。 This is the syntax I'm trying to figure out: 这是我要弄清楚的语法:

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

I would like the result set to look like this: 我希望结果集如下所示:

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

You can do like below way: 1) Create table People with recursive relationship by ParentID column: 您可以按照以下方式进行操作:1)通过ParentID列创建具有递归关系的人表:

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

2) Execute query like below for Alive records: 2)对活动记录执行以下查询:

from p
in this.People
where p.IsAlive 
select p

Please let me know , is this way works for you ? 请让我知道,这样对您有用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM