gpt4 book ai didi

c# - Entity Framework ..自引用表..获取深度=x的记录?

转载 作者:行者123 更新时间:2023-11-30 20:59:05 24 4
gpt4 key购买 nike

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

这应该是什么逻辑?


型号:

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

最佳答案

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

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

但是,据推测这会创建一堆连接表达式,所以这可能不是最佳方式。

关于c# - Entity Framework ..自引用表..获取深度=x的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com