2013-03-26 69 views
1

我成功地在實體框架中使用自引用表。 但我不知道如何獲得所需深度的記錄?實體框架..自引用表..獲取Depth = x的記錄?

應該是什麼這樣做的邏輯是什麼?


型號:

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

什麼是您的RDBMS? – Rachcha 2013-03-26 10:23:15

+0

你的問題很困惑。如果你在C#中工作,你有對象,而不是表格。 – 2013-03-26 10:25:56

+0

MSSQL是我的RDBMS – 2013-03-26 10:35:33

回答

2

理論上你可以創建一個建立動態根據指定的深度級別查詢表達式的方法:

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

但是,大概這會創建一堆連接表達式,所以也許這不是最優化的方式。

+0

這是否會轉換爲T-SQL? – Shimmy 2015-09-26 19:59:44