[entity-framework] How to include a child object's child object in Entity Framework 5

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?

The answer is


With EF Core in .NET Core you can use the keyword ThenInclude :

return DatabaseContext.Applications
 .Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);

Include childs from childrens collection :

return DatabaseContext.Applications
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);

A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.

public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)

{

    foreach (var include in includeProperties)
     {

        query = query.Include(include);
     }

        return query.ToList();
}

I ended up doing the following and it works:

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

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to entity-framework-4

Entity Framework Join 3 Tables Entity framework self referencing loop detected The object 'DF__*' is dependent on column '*' - Changing int to double LEFT JOIN in LINQ to entities? Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties How to include a child object's child object in Entity Framework 5 EF Migrations: Rollback last applied migration? The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Examples related to entity-framework-5

Entity Framework Join 3 Tables The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 EF LINQ include multiple and nested entities Entity Framework 5 Updating a Record Non-static method requires a target How do I enable EF migrations for multiple contexts to separate databases? After updating Entity Framework model, Visual Studio does not see changes Entity Framework Migrations renaming tables and columns

Examples related to entity-framework-4.1

Entity Framework Join 3 Tables How to include a child object's child object in Entity Framework 5 Ignoring a class property in Entity Framework 4.1 Code First The type or namespace name 'Entity' does not exist in the namespace 'System.Data' Validation failed for one or more entities. See 'EntityValidationErrors' property for more details StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First Entity framework code-first null foreign key How do I detach objects in Entity Framework Code First? Entity Framework Code First - two Foreign Keys from same table How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?