Bonomi
Bonomi

Reputation: 2753

Eager loading of 2 levels in entity framework using Lambda Expression

I am working with MS entity-framework core and I am trying to do a eager loading query. For that I have the following method:

public FieldSet GetFieldSetById(int id)
{
    return _context.FieldSet.Include("FieldSetFields.Field").SingleOrDefault(fs => fs.FieldSetId == id);
}

this code works fine, but I was wondering how can I achieve it using the lambda syntax (System.Func).

So far I have this one that works as well, but does not include the "Field".

return _context.FieldSet.Include(e => e.FieldSetFields).SingleOrDefault(fs => fs.FieldSetId == id);

FieldSetFields is a list, and then I cannot call .Field. How can I achieve this?

Upvotes: 1

Views: 72

Answers (1)

DavidG
DavidG

Reputation: 119076

Use ThenInclude:

return _context.FieldSet
    .Include(e => e.FieldSetFields)
        .ThenInclude(fsf => fsf.Field)
    .SingleOrDefault(fs => fs.FieldSetId == id);

Upvotes: 1

Related Questions