Note that the sum of the empty set is defined as 0. (Contrast this to the average of the empty set, which is undefined.)
This means even for nullable types, the results of Sum should be zero (not null) if the set is empty.
using var context = new SomeDbContext(); context.Database.EnsureDeleted(); context.AddRange(new Order { Id = 1, Foo = "ABC" }, new Order { Id = 2, Foo = "DEF" }); context.SaveChanges(); var value = context.Set<Order>().Where(o => o.Id < 0).Select(o => (int?)o.Id).Sum(); Console.WriteLine(value.HasValue ? value.Value.ToString() : "<null>"); public class SomeDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseMongoDB("mongodb://localhost:27017", "SomeDb3") .LogTo(Console.WriteLine, LogLevel.Information); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>(); } } public class Order { public int Id { get; set; } public string Foo { get; set; } }
- is blocked by
-
CSHARP-5680 Sum of empty set cast to a nullable type returns null instead of zero
-
- Backlog
-