IQueryable.Include() gets ignored

前端 未结 2 819
春和景丽
春和景丽 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 07:53

    As you're creating an anonymous object the Parent DbSet Set<Parent>() of the context is not being populated with any data and therefore neither are the Children being stored in the context. One solution could be to add the children to the anonymous object but I'm not sure this would cause them to be added to the Set<Child> DbSet.

    var r2 = ctx.Set<Parent>()
       .Include(p => p.Childs)
       .Where(p => p.Id == 2)
       .Select(p => new { myParent = p, children = p.Childs })
       .ToList();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题