How to enable a child of a child in Entity Framework 5

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

I am struggling to populate a child of a child. Below are my lessons.

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 the GetAll method in the repository returns all applications:

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

The Child class contains a reference to the ChildRelationshipType class. For working with child applications, 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 to indicate that each child should include a ChildRelationshipType object, like what I did above?

+105
entity-framework-5 entity-framework entity-framework-4
Oct 24 '12 at 10:59
source share
4 answers

If you include the System.Data.Entity library, you can use the overload of the Include() method, which takes a lambda expression instead of a string. You can then Select() compared to children with Linq expressions rather than string .

 return DatabaseContext.Applications .Include(a => a.Children.Select(c => c.ChildRelationshipType)); 
+217
Oct 24
source share

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

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

Include children from the children's collection:

 return DatabaseContext.Applications .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1) .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2); 
+47
Mar 28 '17 at 16:56
source share

I ended up doing the following and this works:

 return DatabaseContext.Applications .Include("Children.ChildRelationshipType"); 
+21
Oct 24
source share

A good example of using the Generic Repository template 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(); } 
+3
Apr 08 '16 at 17:52
source share



All Articles