Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 31, 2026

Consecutive .Select() operations with conditional null checks were projecting all properties from earlier selects, generating unnecessary joins and columns in SQL.

users
    .Select(x => new { 
        x.Id, 
        Job = x.Job == null ? null : new { 
            x.Job.Id, 
            Address = new { x.Job.Address.Id, x.Job.Address.Street } 
        } 
    })
    .Select(x => new { 
        x.Id, 
        Job = x.Job == null ? null : new { x.Job.Id }  // Only accessing Id
    })

Generated SQL incorrectly included Address table joins and columns despite the second select only referencing Job.Id.

Changes

Core Fix (NavigationExpandingExpressionVisitor.ExpressionVisitors.cs)

  • Modified IncludeExpandingExpressionVisitor.VisitMember() to extract specific members from NavigationTreeExpression anonymous types instead of reconstructing the entire structure
  • When accessing x.Job.Id on a NavigationTreeExpression containing new { Id = ..., Address = ... }, now visits only the Id argument

Tests

  • Added Consecutive_selects_with_conditional_projection_should_not_include_unnecessary_joins test case
  • Verifies generated SQL excludes unreferenced navigation joins
Original prompt

This section details on the original issue you should resolve

<issue_title>Checking parameter for null causes incorrect projections translation</issue_title>
<issue_description>### Bug description

This is a copy of npgsql/efcore.pg#3295

Hello,

When checking a joined entity for NULL the further projecting of joined table does not take effect causing always selecting all fields and all subsequent joins if any.

Suppose having following entity hierarchy: User -> Job? -> Address

class User {
  public long Id { get; set; }
  public long? JobId { get; set; }
  // other unrelated properties
}

class Job {
 public long Id { get; set; }
 public long AddressId { get; set; }
 // other unrelated properties
}

class Address {
 public long Id { get; set; }
 // other unrelated properties
}

The following linq query

        var claim = await users
            .Select(x => new
            {
                x.Id,
                Job = x.Job == null ? null : new
                {
                    x.Job.Id,
                    Address = new
                    {
                        x.Job.Address.Id,
                        x.Job.Address.Street
                    }
                }
            })
            .Select(x => new
            {
                x.Id,
                Job = x.Job == null ? null : new
                {
                    x.Job.Id
                }
            })
            .Where(x => x.Id == 14501)
            .FirstOrDefaultAsync();

produces this sql:

SELECT c."Id", c0."Id", FALSE, c1."Id", c1."Street"
FROM "User" AS c
INNER JOIN "Job" AS c0 ON c."JobId" = c0."Id"
INNER JOIN "Address" AS c1 ON c0."AddressId" = c1."Id"
WHERE c."Id" = 14501

It includes join to Address table, even though it is not selected in the last Select method.

You may ask why doing consequent selects, the answer is the part before second select may come from elsewhere as IQueryable which you want to further narrow down.

Anyways, is that expected? And is it possible to workaround?

Your code

see description

Stack traces


Verbose output


EF Core version

9.0.0

Database provider

Npgsql.EntityFrameworkCore.PostgreSQL.9.0.1

Target framework

No response

Operating system

MAC OS

IDE

Jetbrains Rider</issue_description>

Comments on the Issue (you are @copilot in this section)

@cincuranet Small repro:
using Microsoft.EntityFrameworkCore;

using var db = new MyContext();
Console.WriteLine(db.Users
    .Select(x => new
    {
        x.Id,
        Job = x.Job == null ? null : new
        {
            x.Job.Id,
            Address = new
            {
                x.Job.Address.Id,
                x.Job.Address.Street
            }
        }
    })
    .Select(x => new
    {
        x.Id,
        Job = x.Job == null ? null : new
        {
            x.Job.Id
        }
    })
    .Where(x => x.Id == 14501)
    .ToQueryString());

class MyContext : DbContext
{
    public DbSet<User> Users { get; set; } = null!;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite();
    }
}
class User
{
    public long Id { get; set; }
    public long? JobId { get; set; }
    public Job? Job { get; set; }
}
class Job
{
    public long Id { get; set; }
    public long AddressId { get; set; }
    public Address Address { get; set; } = null!;
}
class Address
{
    public long Id { get; set; }
    public string Street { get; set; } = null!;
}

BTW, removing the second conditional (the x.Job == null ? null : new) "fixes" it. </comment_new>


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI and others added 5 commits January 31, 2026 21:46
When two consecutive Select() operations are applied with conditional expressions,
the second Select was including unnecessary joins and columns from the first Select.

Root cause: In IncludeExpandingExpressionVisitor.VisitMember, when accessing a
specific member of a NavigationTreeExpression with a NewExpression (anonymous type),
the code was reconstructing the entire anonymous type instead of just extracting
the accessed member.

Fix: Modified VisitMember to detect when a member is accessed on a NavigationTreeExpression
with a NewExpression value, and directly visit only the specific argument corresponding to
that member, avoiding reconstruction of the entire anonymous type.

This ensures that expressions like:
  .Select(x => new { x.Job.Id, x.Job.Address.Street })
  .Select(x => new { x.Job.Id })

Only include Job.Id in the final SQL, not Address properties.

Fixes #XXXXX

Co-authored-by: roji <[email protected]>
Copilot AI changed the title [WIP] Fix parameter check causing incorrect projections translation Fix unnecessary joins in consecutive Select projections with conditionals Jan 31, 2026
Copilot AI requested a review from roji January 31, 2026 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Checking parameter for null causes incorrect projections translation

2 participants