Select multiple nested levels of child tables in Entity Framework Core

24,095

Solution 1

You can use the keyword ThenInclude instead

e.g.

var company = context.Companies
             .Include(co => co.Employees).ThenInclude(emp => emp.Employee_Car)
             .Include(co => co.Employees).ThenInclude(emp => emp.Employee_Country)
             .FirstOrDefault(co => co.companyID == companyID);

Solution 2

Also, the .ThenInclude intellisense for only works up to the 3rd level, for example:

_Context.A.Include(a => a.B).ThenInclude(B => B.C).ThenInclude(C => C.D)

The last part of that statement:

 .ThenInclude(C => C.D)

won't show "D", so you have to type D in yourself, then wait for a short period of time for the compilation error to disappear!

Share:
24,095
zoaz
Author by

zoaz

dev

Updated on July 20, 2022

Comments

  • zoaz
    zoaz over 1 year

    I want to get multiple nested levels of child tables in Entity Framework Core using eager loading. I don't think lazy loading is implemented yet.

    I found an answer for EF6.

    var company = context.Companies
                     .Include(co => co.Employees.Select(emp => emp.Employee_Car))
                     .Include(co => co.Employees.Select(emp => emp.Employee_Country))
                     .FirstOrDefault(co => co.companyID == companyID);
    

    My problem is that Select is not recognized in EF Core

    Error CS1061 'Employees' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'Employees' could be found (are you missing a using directive or an assembly reference?)

    My included namespaces:

    using MyProject.Models;
    using Microsoft.Data.Entity;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    

    What is the alternative for Select in EF Core.

  • JasonX
    JasonX about 7 years
    Am I insane, or does this no longer work in EF Core 1.1.0? .ThenInclude treats the parent as an ICollection, offering me the collection properties instead of a single element's properties :/
  • Daniel Zolnai
    Daniel Zolnai almost 7 years
    @JasonX It is a bug in IntelliSense, just write you query as it would be an entity and it will work fine.
  • cdavid
    cdavid about 6 years
    @DanielZolnai did you report the bug by any chance - or how did you find it? Do you have a link to the GitHub issue?
  • ruffin
    ruffin about 6 years
    @cdavid It's listed here in the docs, and here on github. Unrelated: Painful that I have to do the .Include twice for grandchildren from the same child (in your (firste's) case, Employees). But excellent example; thanks.
  • EGP
    EGP about 3 years
    Using dotnet 5 and EF Core, intellisense is working at 3rd and 4th level (and possibly beyond).
  • Chris J
    Chris J about 3 years
    Nice. About time!