knappster
knappster

Reputation: 401

Self-referencing relationship in Entity Framework with child includes

Is there any way of including child object within a self referencing relationship. For example, I have an object like this:

class Activity
{
    public int Id {get;set;}
    public String Name {get;set;}

    public IList<Document> Documents {get;set;}
    public IList<Activity> ChildActivities {get;set;}
}

and I call it in linq like so:

from act in context.Activities.Include("Documents").Include("ChildActivities")
                      where act.Id == id
                      select act;

but the ChildActivities -> Documents object is always null, is there any way of including these as well?

Upvotes: 0

Views: 2457

Answers (2)

Slauma
Slauma

Reputation: 177163

You can use "dotted paths" to include deeper levels of navigation properties. For your example you can write:

from act in context.Activities
    .Include("Documents")
    .Include("ChildActivities.Documents")
where act.Id == id
select act;

An explicit Include("ChildActivities") is not necessary here because EF will include all entities automatically that are on the path to the included final navigation property.

BTW: If you are using EF >= 4.1 you have a strongly typed version for Include available that takes a lambda expression as parameter:

using System.Data.Entity; // <- this namespace is required for the lambda-Include

//...

from act in context.Activities
    .Include(a => a.Documents)
    .Include(a => a.ChildActivities.Select(ca => ca.Documents))
where act.Id == id
select act;

Upvotes: 4

Chris
Chris

Reputation: 8656

One way would be to take advantage of Entity Framework's Lazy Loading features.

You would need to alter your object slightly by adding to virtual keyword to your navigation properties so they meet EF requirements for creating POCO proxies:

public class Activity
{
    public int Id {get;set;}
    public String Name {get;set;}

    public virtual IList<Document> Documents {get;set;}
    public virtual IList<Activity> ChildActivities {get;set;}
}

You should now be able to access the Documents of your ChildActivities without having to explicitly load them (either via Eager/Explicit loading).

Upvotes: 0

Related Questions