IQueryable.Include() gets ignored

前端 未结 2 818
春和景丽
春和景丽 2021-01-19 07:35

I have Parent and Child entities related to each other as 1 to M. I need to query childs together with parents within a single SQL query, but the <

2条回答
  •  伪装坚强ぢ
    2021-01-19 08:04

    This is a general problem in all versions of EF known to me. EF tries hard to pass the 'includes' as far as possible, but when "the shape of the query changes", the 'includes' are irreversibly lost.

    The "shape" of the query changes for example, when:

    • a projection is used (select not whole object but just some fields, or different object)
    • a group-by or other aggregation is used
    • .. and probably in some more cases, which currently I dont remember.

    Sadly, I also dont remember where on MSDN I stumbled upon the "shape of the query" explanation. If I find it, I'll drop here a link.

    The solution is actually quite simple: simply specify the 'include' part not early, but at the final result. So, instead of set.include(x) at beginning, do .Select( .. => new { .., x }) to include the 'x' manually. It also works during grouping, as you can do a projection there too.

    However, this is not a solution. This is a manual patch/hotfix, which does not solve anything. Considering that you might want to expose a "IQueryable<>" through some interface, you may like to expose a "base query" with some things already .Included. And of course, this is simply not possible to do in a general way, as if the client of the interface does a projection or grouping, he will lose the includes and he will not even know which ones should be. For me, this is a major deficiency in EF.

    EDIT: just found one: .Include in following query does not include really Not MSDN, but just as good.

提交回复
热议问题