2

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

这应该是什么逻辑?


模型 :

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; }
}
4

1 回答 1

4

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

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();
    }
}

但是,大概这会创建一堆连接表达式,所以这可能不是最优化的方式。

于 2013-03-26T11:57:43.897 回答