Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Eager Loading Multiple Levels Exception

Ok, so according to this page, the Entity Framework should eagerly load multiple levels by using a Select within the Include method.

I have the following code:

var reports = _context.Reports
    .Include(rt => rt.Fields)
    .Include(rt => rt.Fields.Select(f => f.FieldType))
    .Include(rt => rt.Fields.Select(f => f.FieldType.FieldIdentifier));

Yet this throws an InvalidOperationException - "Invalid type of expression" on the call to the second include. The Exception is coming from EntityFrameworkHelper.CollectRelationalMemebers.

I also tried using strings to Include related properties, but that failed as well (I'd rather avoid using the strings if at all possible).

I'm using the EF 5.0 DLL for .NET 4.0. My EF classes are old-fashioned database-first EntityObjects.

Does anyone know the cause and if there's anything I can do about this exception?

EDIT:

When using the string version:

var reports = _context.Reports
    .Include("Fields")
    .Include("Fields.FieldType")
    .Include("Fields.FieldType.FieldIdentifier"));

It throws InvalidOperationException - Invalid type of Expression.

like image 837
MgSam Avatar asked Feb 20 '13 19:02

MgSam


1 Answers

You have redundant includes. You only need the last include, which will include anything in that path. Example:

var reports = _context.Reports
    .Include(rt => rt.Fields.Select(f => f.FieldType.FieldIdentifier));
like image 63
Jace Rhea Avatar answered Nov 03 '22 01:11

Jace Rhea