自我参照关系:选择儿童和孙子女

时间:2011-06-22 23:36:38

标签: entity-framework ado.net entity-framework-4

我的ADO.Net实体数据模型下面有一个名为ABC的模型(以自引用表为模型)。

ABC Properties are
----------
ParentID
Child ID

ABC Navigation Properties are
----------
ParentCategory (refers to the parent category or the 0..1 side of the relationship)
SubCategories (refers to the children or the * side of the relationship, represents the navigation property for the children)

我想为特定的ParentID(即不是层次结构的顶部)选择子孙。我怎样才能做到这一点。有人可以提出一个例子。感谢


我在vb中尝试了下面提出的解决方案,但它只加载一个级别;

我在VB中这样做,所以向C#程序员道歉。

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
        Dim ctx = New links2Entities
        Dim query = From c In ctx.PBS.Include("SubCategory.SubCategory") Where (c.Parent_ID = 7)
        For Each result As PB In query
            Debug.WriteLine("ID: {0}", result.Child_ID)
        Next
    End Sub

1 个答案:

答案 0 :(得分:5)

如果您需要按其ID选择实体并急切加载其子级的两个级别,则需要执行以下操作:

var query = context.ABC.Include("SubCategories.SubCategories")
                       .Where(e => e.Id == id);

对于EF 4.1,它应该是:

var query = context.ABS.Include(e => e.SubCategories.Select(s => s.SubCategories))
                       .Where(e => e.Id == id);

如果您需要急切加载任何深度的所有子类别,则无法告诉它EF。