linq2db / linq2db.EntityFrameworkCore

Bring power of Linq To DB to Entity Framework Core projects
MIT License
462 stars 38 forks source link

SUM does not coalesce #135

Closed Atulin closed 3 years ago

Atulin commented 3 years ago
.Set(s => s.WordCount, s => s.Chapters
    .Where(c => c.IsPublished)
    .Sum(c => c.WordCount))

In this scenario, if no chapters are published, the result will be null. It cannot be coalesced with ?? since Sum() returns a non-nullable value, so there's no good way of giving this operation a default value of 0.

The workaround is

.Set(s => s.WordCount, s => ((int?)s.Chapters
    .Where(c => c.IsPublished)
    .Sum(c => c.WordCount)) ?? 0)

but then the IDE complains that the left side of ?? will never be null.

MaceWindu commented 3 years ago

maybe .Sum(c => (int?)c.WordCount) ?

Atulin commented 3 years ago

It does appease the linter, yes, but it's still a workaround.

MaceWindu commented 3 years ago

If I understand your problem, that's a correct workaround. .net's Enumerable.Sum aggregate signature doesn't match same of sql COUNT and return non-nullable type when aggregated over non-nullable sequence.

sdanyliv commented 3 years ago

As designed.