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

后端 未结 4 1364
鱼传尺愫
鱼传尺愫 2020-11-27 02:21

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 m

相关标签:
4条回答
  • 2020-11-27 03:03

    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);
    
    0 讨论(0)
  • 2020-11-27 03:05

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

    return DatabaseContext.Applications
         .Include(a => a.Children.Select(c => c.ChildRelationshipType));
    
    0 讨论(0)
  • 2020-11-27 03:12

    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();
    }
    
    0 讨论(0)
  • 2020-11-27 03:17

    I ended up doing the following and it works:

    return DatabaseContext.Applications
         .Include("Children.ChildRelationshipType");
    
    0 讨论(0)
提交回复
热议问题