admin

实体框架..自引用表..获取深度= x的记录?

sql

我在实体框架中成功使用了自引用表。但是我不知道如何获取所需深度的记录?

这样做的逻辑应该是什么?


模型 :

public class FamilyLabel
{
    public FamilyLabel()
    {
        this.Children = new Collection<FamilyLabel>();
        this.Families = new Collection<Family>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int FamilyLabelId { get; set; }
    public string FamilyLabelName { get; set; }

    public virtual FamilyLabel Parent { get; set; }

    public int JamaatId { get; set; }
    public virtual Jamaat Jamaat { get; set; }

    public virtual ICollection<Family> Families { get; set; }
    public virtual ICollection<FamilyLabel>  Children { get; set; }
}

阅读 44

收藏
2021-06-07

共1个答案

admin

从理论上讲,您可以创建一个方法,该方法根据指定的深度级别动态构建查询表达式:

context.FamilyLabels.Where(x => 
    x.Parent. ... .Parent != null &&
    x.Parent.Parent ... .Parent == null);

以下实现可以达到目的:

public static IList<FamilyLabel> Get(DbConnection connection, int depth)
{
    var p = Expression.Parameter(typeof(FamilyLabel));
    Expression current = p;

    for (int i = 0; i < deep; i++)
    {
        current = Expression.Property(current, "Parent");
    }

    var nullConst = Expression.Constant(null, typeof(FamilyLabel));

    var predicate = Expression.Lambda<Func<FamilyLabel, bool>>(
        Expression.AndAlso(
            Expression.NotEqual(current, nullConst),
            Expression.Equal(Expression.Property(current, "Parent"), nullConst)), p);

    using (MyDbContext context = new MyDbContext(connection))
    {
        return context.FamilyLabels.Where(predicate).ToList();
    }
}

但是,大概这会创建一堆联接表达式,因此这可能不是最佳方法。

2021-06-07