Erwin1
Erwin1

Reputation: 640

Self Referencing Relationship: Selecting children and grandchildren

My ADO.Net Entity Data Model has a model called ABC below (modeled after a self-referencing table).

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)

I want to select the children and grandchildren for a specific ParentID (i.e. not the top of the hierarchy ). How can I accomplish this. Can someone please propose an example. Thanks


I have tried the solution proposed below in vb, but it is only loading one level;

I am doing this in VB so apologies to C# programmers.

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

Upvotes: 0

Views: 588

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364369

If you need to select entity by its Id and eager load two levels of its children you need to do:

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

In case of EF 4.1 it should be:

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

If you need to eager load all sub categories in any depth there is not way to tell it EF.

Upvotes: 5

Related Questions