Entity Framework Core SelectMany then Include

.net-core c# entity-framework-core

Question

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

1
6
6/20/2018 3:29:15 PM

Accepted Answer

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)
7
6/13/2017 11:35:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow