Skip to content

Checking parameter for null causes incorrect projections translation #3295

@elementum

Description

@elementum

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?

Environment

Target Framework: net8.0
Npgsql.EntityFrameworkCore.PostgreSQL: 8.0.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions