【问题标题】:How can I exclude specific association records in a LINQ to SQL query?如何排除 LINQ to SQL 查询中的特定关联记录?
【发布时间】:2015-06-04 20:37:33
【问题描述】:

假设我有以下数据:

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 为真的记录,从而排除任何 Alive 为假的记录。这是我想弄清楚的语法:

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)

【问题讨论】:

  • 如果Child 4 (Alive = false)Grandchild 4 (alive = true) 会发生什么? Grandchild 对象实际上Child 对象的子对象吗?
  • 是的,他们实际上是孩子。想象一个 People 表,其 ParentId 列是同一个表的 FK。所以在你的例子中,孙子 4 将被排除在外,因为孩子 4 不活着。
  • 他们有Parent 的导航属性,还是只有Id
  • 他们确实有一个 Parent 属性
  • 你试过where p.IsAlive && (p.Parent != null && p.Parent.IsAlive || p.Parent == null),然后groupby p.Parent

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


【解决方案1】:

您可以通过以下方式进行操作: 1) 通过 ParentID 列创建具有递归关系的表 People:

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) 对 Alive 记录执行如下查询:

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

请告诉我,这种方式适合你吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多