Repository navigation
Description
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
maumar commentedon May 20, 2020
dupe of / related to #20633
Query: Don't read default value from databases
Query: Don't read default value from databases
Query: Don't read default value from databases (#21668)