【问题标题】:Entity Framework Recursive Relationship Hierarchical Data实体框架递归关系分层数据
【发布时间】:2018-06-06 04:50:12
【问题描述】:

Entity Framework 是否支持某种递归 LINQ,还是我必须用 SQL 编写查询? (使用 ParentId - 典型的类别子类别问题)

【问题讨论】:

  • 您到底想达到什么目标?请具体一点。
  • @cloudikka 基本操作,例如取出整个层次结构
  • (1) 没有。它不是 EF 特定的,而是 Queryable 和一般的表达式树限制 - 无法定义递归表达式。 (2) 由于 EF 导航属性修复,可以采用整个层次结构。但是,使用单个 L2E 查询是不可能的(除非您加载全部三个然后在内存上应用过滤器)。见Is recursive query possible in LINQ
  • @IvanStoev:不完全是真的表达式树有这样的限制。您可以编写递归表达式。例如Factorial expression.
  • @cloudikka 但它在内部使用Finc<..>。我的意思是纯表达式(这是可查询的要求,因为它们必须是可识别和可翻译的,对于未知的Func<...> 代码不能这么说)

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6


【解决方案1】:

我认为您可以通过在扩展方法中使用Include 方法来解决它,以仅获取一部分层次结构或全部获取。即使它可以生成非常丑陋的 SQL。

using(var context = new HierarchyContext())
{
    var depth = context
                .Categories
                .IncludeHierarchy(3, nameof(Category.Children));

    var root = depth.Single(c => c.Id == 2);
}


public static IQueryable<T> IncludeHierarchy<T>(this IQueryable<T> source, 
uint depth, string propertyName)
where T : Category
{
    var temp = source;

    for (var i = 1; i <= depth; i++)
    {
        var sb = new StringBuilder();

        for (var j = 0; j < i; j++)
        {
            if (j > 0)
            {
                sb.Append(".");
            }

            sb.Append(propertyName);
        }

        var path = sb.ToString();

        temp = temp.Include(path);
    }

    var result = temp;

    return result;
}

public class Category
{    
   // Primary key    
   public int Id { get; set; }

   // Category name    
   public string Name { get; set; }

   // Foreign key relationship to parent category    
   public int ParentId { get; set; }

   // Navigation property to parent category    
   public virtual Category Parent { get; set; }

   // Navigation property to child categories    
   public virtual ICollection<Category> Children { get; set; }    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多