Select multiple nested levels of child tables in Entity Framework Core

Entity Framework-Core

Entity Framework-Core Problem Overview


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.

Entity Framework-Core Solutions


Solution 1 - Entity Framework-Core

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 - Entity Framework-Core

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzoazView Question on Stackoverflow
Solution 1 - Entity Framework-CoredevfricView Answer on Stackoverflow
Solution 2 - Entity Framework-CoreChris JView Answer on Stackoverflow