Skip to content

Query: consider expanding null safety beyond nav rewrite #12284

@AlekseyMartynov

Description

@AlekseyMartynov

Version: 2.1.1-rtm-30843 (nightly build)

Please consider this example:

Entity:

public class TestEntity {
    public int ID { get; set; }
    public DateTime? Date { get; set; }
}

Ensure there are records:

var set = context.Set<TestEntity>();
set.Add(new TestEntity());
context.SaveChanges();

Now, this is a query that is fully translated into SQL:

var result = set
    .GroupBy(obj => new {
        Year = (int?)obj.Date.Value.Year
    })
    .Select(g => new {
        g.Key.Year,
        Count = g.Count()
    })
    .ToArray();
SELECT DATEPART(year, [obj].[Date]) AS [Year], COUNT(*) AS [Count]
FROM [TestEntity] AS [obj]
GROUP BY DATEPART(year, [obj].[Date])

However, if I modify it as follows:

var result = set
    .GroupBy(obj => new {
        Year = (int?)obj.Date.Value.Year
    })
    .Select(g => new {
        g.Key.Year,
        Count = g.Count(i => i.Date != null) // change here: count only non-null dates
    })
    .ToArray();

then it is partially translated into SQL:

SELECT [obj].[ID], [obj].[Date]
FROM [TestEntity] AS [obj]
ORDER BY DATEPART(year, [obj].[Date])

but grouping is done in-memory.

It fails with Nullable object must have a value.

I understand that for LINQ 2 Objects I would have to add null-conditional:

Year = obj.Date == null ? null : (int?)obj.Date.Value.Year

Finally the question:

Should the user of EF Core proactively take care of null safety as with L2O? Or on the contrary it is a bug and EF Core in-memory magic must hide it from me?

Metadata

Metadata

Assignees

No one assigned
    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions