Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core SelectMany then Include

I cant seem to figure out how to get EF Core to include / load related objects when using SelectMany.

context.MyObject
       .Where(w => w.Id == Id)
       .SelectMany(m => m.SubObject)
       .Include(i => i.AnotherType)

Would have thought something like the above would work, however the collapsed SubObject collection has the AnotherObject being null and not included.

Been searching for hours.

Any help would be appreciated.

Thanks

like image 374
Mike U Avatar asked Jun 13 '17 10:06

Mike U


1 Answers

Would have thought something like the above would work

It used to work in EF6, but currently is not supported by EF Core - it allows you to use eager load only the entity which the query starts with, as mentioned in the Loading Related Data - Ignored Includes section of the documentation:

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.

So to get the eager loading work in your scenario, the query should be like this (assuming you have inverse navigation or FK property in SubObject):

context.SubObject
       .Where(so => so.Object.Id == Id) // or so.ObjectId == Id
       .Include(i => i.AnotherType)
like image 161
Ivan Stoev Avatar answered Sep 20 '22 11:09

Ivan Stoev