How to include a child object's child object in Entity Framework 5

Posted by Brendan Vogt on Stack Overflow See other posts from Stack Overflow or by Brendan Vogt
Published on 2012-10-24T10:59:14Z Indexed on 2012/10/24 11:00 UTC
Read the original article Hit count: 368

I am using Entity Framework 5 code first and ASP.NET MVC 3.

I am struggling to get a child object's child object to populate. Below are my classes..

Application class;

public class Application
{
     // Partial list of properties

     public virtual ICollection<Child> Children { get; set; }
}

Child class:

public class Child
{
     // Partial list of properties

     public int ChildRelationshipTypeId { get; set; }

     public virtual ChildRelationshipType ChildRelationshipType { get; set; }
}

ChildRelationshipType class:

public class ChildRelationshipType
{
     public int Id { get; set; }

     public string Name { get; set; }
}

Part of GetAll method in the repository to return all the applications:

return DatabaseContext.Applications
     .Include("Children");

The Child class contains a reference to the ChildRelationshipType class. To work with an application's children I would have something like this:

foreach (Child child in application.Children)
{
     string childName = child.ChildRelationshipType.Name;
}

I get an error here that the object context is already closed.

How do I specify that each child object must include the ChildRelationshipType object like what I did above?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about entity-framework