Entity Framework Core SelectMany then Include

不羁的心 提交于 2020-01-14 08:58:11

问题


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:


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)


来源:https://stackoverflow.com/questions/44519325/entity-framework-core-selectmany-then-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!