Select multiple nested levels of child tables in Entity Framework Core

entity-framework-core

Question

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.

Accepted Answer

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);


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why