【问题标题】:Finding a TOP LEVEL parent in Entity Framework Query在实体框架查询中查找 TOP LEVEL 父级
【发布时间】:2013-07-18 00:02:07
【问题描述】:

我有两张表如下

桌人

  Id   Name
   1    A
   2    B
   3    C
   4    D
   5    E

表关系层次结构

ParentId   CHildId
   2         1
   3         2
   4         3

这将形成一个树状结构

      D
      |
      C
      |
      B
      |
      A

ParentId 和 ChildId 是 Person 表的 Id 列的外键

让我们假设 EF 实体名称是表名称。我需要找到每个人的顶级家长。结果集应如下所示

 PersonId PersonName TopLevelPArentID TopLevelPArentName

谁能建议任何 LINQ 或 LINQ to Entity Query?

【问题讨论】:

  • 我认为您需要将所有数据放入内存并构建树。 EF 不会递归搜索父母。你将如何用普通的 SQL 实现它?
  • 这是否意味着我需要在 GetRelationHierarchy() 方法上执行 .ToList?例如context.RelationHierarchy.ToList();我需要对这些数据应用逻辑

标签: c# linq entity-framework-4


【解决方案1】:

我假设最高父级的 ParentId 设置为 NULL? 使用这个假设,我们可以使用递归函数遍历每个 Person。

public YourMainFunction(){
    List<Person> allPersons = entityContext.Person.ToList();
    List<KeyValuePair<Person, Person>> personAndParents = new List<KeyValuePair<Person, Person>>();
    foreach(Person p in allPersons){
        personAndParents.Add(new KeyValuePair<Person, Person>(p, GetTopParent(p)));
    }
}
//Now you have a list of each Persons Parents in a key/value pair list.

public Person GetTopParent(Person p){
    if(p.RelationHierarchy.Count(r=>r.ParentId != null) == 0){
        return p;
    }
    else{
        return GetTopParent(p.RelationHierarchy.FirstOrDefault(r=>r.ParentId != null).Person1); //This should be the parent relation, not the child relation, im not sure what you have named the relations.
    }
}

【讨论】:

  • 顶级父级在 Hierarchy 表父子关系中没有任何行,即在 ChildId 列中将没有 Person 的顶级父级的行
  • 不应该是递归调用吗?
  • 我做了一些编辑,现在使用 RelationHierarchy 表。 Foreach 人员检查它是否在 RelationHierarchy 表中有父级。如果不是它是父母,否则检查 RelationHierarchy.Parent 等等。它是递归的,因为 GetTopParent 正在调用自己。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2013-03-17
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多