Eager load EF Core collection type members

Viewed 1576

Assume I have two classes:

class Foo
{
    List<Bar> someList
}

class Bar
{
    string a;
}

I want to eager load a Foo instance from EF Core and include Foo.someList.a

When I try to straight up write an include such as

.Include("Foo.someList.a")

I get an exception:

An error was generated for warning 'Microsoft.EntityFrameworkCore.Query.InvalidIncludePathError':

Unable to find navigation 'Foo.someList.a' specified in string based include path 'a'.

This exception can be suppressed or logged by passing event ID 'CoreEventId.InvalidIncludePathError' to the 'ConfigureWarnings' method in

'DbContext.OnConfiguring' or 'AddDbContext'."} System.InvalidOperationException

2 Answers

Take a look at this reference page from Microsoft.

What would work in your case is to include multiple levels, like this:

var result = context.Foos
    .Include(foo => foo.someList)
    .ThenInclude(bar => bar.a);

Edit: OP has manifested preference for the overload of Include that takes a string instead.

var result = context.Foos
    .Include("someList.a");

You should write your code as shown here:

 var data = _context.Foos.Include(b => b.someList).ThenInclude(b => b.a);
Related