Skip to content

Subquery materializes zero in place of null #21002

Closed

Description

@bachratyg

When materializing an aggregate subquery a null value is materialized as zero.

Steps to reproduce

class Table
{
    public int Id { get; set; }
}
class Db : DbContext
{
    public DbSet<Table> Table { get; set; }
}
// config
services.AddDbContext<Db>(opts => opts.UseSqlServer(connStr, sql => sql.UseRelationalNulls()));
// the actual query
var q = from t in db.Table
        select new
        {
            A = t.Id,
            B = db.Table
                .Where(t2 => t2.Id > 10000/*some ridiculously large number that makes this condition always false but prevents any optimization*/)
                .Max(t2 => t2.Id),
        };
var r = await q.ToListAsync();

The raw sql would look something like this:

SELECT
	[t0].[Id] AS [A],
	(
		SELECT MAX([t].[Id])
		FROM [Table] AS [t]
		WHERE [t].[Id] > 10000
	) AS [B]
FROM [Table] AS [t0]

When executed directly on the db it would yield the following values:
A B
1 null
2 null

However EFCore materializes the following:
A B
1 0
2 0

EF6 threw an exception in this case (attempted to materialize null as a non-null value, can't remember the exact wording of the exception). Is this behavior intentional?

When the subquery is forced to be nullable, e.g.

var q = from t in db.Table
        select new
        {
            A = t.Id,
            B = db.Table
                .Where(t2 => t2.Id > 10000/*some ridiculously large number that makes this condition always false but prevents any optimization*/)
                .Max(t2 => (int?)t2.Id),
        };

then the expected null values are materialized in B.

I'm also fiddling with the provider model extending the relational base provider and return null values in the DbDataReader however EFCore still tries to call DbDataReader.GetInt32 for the B column (and fails miserably with an exception) regardless of the nullability of B. I'm not sure what's going on here, this looks like different behavior than SQL Server.
Scratch that. It was a bug in my code.

Further technical details

EF Core version: 3.1.4
Database provider: Microsoft.EntityFrameworkCore.SqlServer)
Target framework: .NET Core 3.1
Operating system: Windows 10 (10.0.18363.836)
IDE: Visual Studio 2019 16.6.0

Activity

  1. maumar commented on May 20, 2020

    @maumar
    Contributor

    dupe of / related to #20633

  2. added this to the 5.0.0 milestone on May 22, 2020
  3. added 3 commits that reference this issue on Jul 17, 2020
    078f68e
    4602ba3
    3ebfde7
  4. modified the milestones: 5.0.0, on Jul 18, 2020
  5. modified the milestones: , 5.0.0 on Nov 7, 2020
  6. 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

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions