在嵌套层次结构中导航的 EF5 代码优先迁移

EF5 code first migrations navigating inside nested hierarchy

数据库是使用代码优先迁移生成的。

我有这样的 parent child 关系,每个人都有 children 并且 children 可能有自己的 children 等。

public class Person
{
    public string Name { get; set; }
    public bool Flagged { get; set; }
    public virtual ICollection<Person> Children { get; set; }
    public virtual Person Master { get; set; }
    ...
}

找到这些东西的最有效方法是什么?到目前为止,我一直在使用 递归查询 ,它看起来很慢而且不是一件好事。我读到了 Common Table Expressions,但我不确定这是否适合我的需要并支持 EF code first migrations

  1. Person 找到第一个 Flagged = true 的 Master。
  2. 人发现所有嵌套children.
  3. Person 找到所有嵌套的 children,其 Flagged = true。

A​​FAIK Entity framework 不支持通用 Table 表达式。您可能应该继续使用数据库视图。对我来说,获取 parents 和 children 的查询看起来像这样。

    WITH Children AS 
 (
  SELECT a.*
  FROM dbo.Persons a
  WHERE Id = 14
  UNION ALL
  SELECT a.*
  FROM dbo.Persons a JOIN Children c ON a.IdParentPerson = c.id
  )
  SELECT *
  FROM Children 
  /*WHERE Children.Flagged = true*/ /*IF REQUIRED*/

    WITH Parents AS 
 (
  SELECT a.*
  FROM dbo.Persons a
  WHERE Id = 16
  UNION ALL
  SELECT a.*
  FROM dbo.Persons a JOIN Parents c ON a.Id = c.IdParentPerson
  )
  SELECT *
  FROM Parents
  WHERE Parents.Flagged = true

然后在 DbSet 上使用它,例如

var id = YOUR_ID;
using(var context = new Context())
{
    var query = context.Set<GroupEntity>().SqlQuery(
    " WITH Parents AS  " +
    " ( " +
    " SELECT a.* " +
    " FROM dbo.Persons a " +
    " WHERE Id = @Id " +
    " UNION ALL " +
    " SELECT a.* " +
    " FROM dbo.Persons a JOIN Parents c ON a.Id = c.IdParentPerson " +
    " ) " +
    " SELECT * " +
    " FROM Parents " +
    " WHERE Parents.Flagged = true "
    , new SqlParameter("@Id", id));  
}