Sum of empty set cast to a nullable type returns null instead of zero

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Fixed
    • Priority: Unknown
    • 10.0.3, 9.1.3, 8.4.3
    • Affects Version/s: None
    • Component/s: None
    • None
    • None
    • Dotnet Drivers
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      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; }
      }
      

            Assignee:
            Arthur Vickers
            Reporter:
            Arthur Vickers
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: