Skip to content

Query: correlated collection optimization is broken for queries containing top level First/FirstOrDefault/Single/SingleOrDefault #10813

Closed

Description

@maumar

Repro:

var result = ctx.Parents.Select(p =>
new
{
    Children = p.Children
}).FirstOrDefault();

Problem here is that when we rewrite QM to create query that fetches inner elements, we produce join between inner elements and cloned parent query model. However, if parent model contains result operators that change cardinality, we would clone it also and hence produce invalid QM.

Activity

  1. self-assigned this
    on Jan 30, 2018
  2. added a commit that references this issue on Jan 31, 2018
  3. added this to the 2.1.0 milestone on Feb 2, 2018
  4. smitpatel commented on Feb 2, 2018

    @smitpatel
    Contributor

    In the presence of Single value from sequence result operator, we should not be doing any optimization. Rather than we should just use N+1 mode of evaluation since it would run 2 queries anyway. It gives us benefit that 2nd query is filtered based on a parameter rather than a join (also no order by is needed in 2nd query) which would be efficient than running a normal collection query.

  5. maumar commented on Feb 5, 2018

    @maumar
    ContributorAuthor

    @smitpatel correlated collections optimization doesn't work if the outer is using outer parameter, so in case of multi-level correlation we would be producing inefficient queries. We could make the optimization you suggest once/if #10877 is addressed

  6. added a commit that references this issue on Feb 5, 2018
  7. maumar commented on Feb 5, 2018

    @maumar
    ContributorAuthor

    fixed in d787c13

  8. smitpatel commented on Feb 11, 2018

    @smitpatel
    Contributor

    Re-opening this. This is partially fixed. We need tracking issue to do outer parameter injection for single record collection query. Either we use this or file a new one. For include pipeline (perhaps older one) #2182

  9. maumar commented on Feb 12, 2018

    @maumar
    ContributorAuthor

    @smitpatel #10877 is already tracking this (see one of the comments)

  10. maumar commented on Feb 28, 2018

    @maumar
    ContributorAuthor

    Workaround:

    First/FirstOrDefault:

    var result = ctx.Parents.Select(p =>
    new
    {
        Children = p.Children
    }).Take(1).ToList().FirstOrDefault();

    Single/SingleOrDefault:

    var result = ctx.Parents.Select(p =>
    new
    {
        Children = p.Children
    }).Take(2).ToList().SingleOrDefault();
  11. modified the milestones: , 2.1.0 on Nov 11, 2019
  12. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions