Average over empty collection of nullable types throws

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Unresolved
    • Priority: Unknown
    • None
    • Affects Version/s: None
    • None
    • None
    • Dotnet Drivers
    • None
    • None
    • None
    • None
    • None
    • None

      In LINQ to Objects and other EF Core providers, calling Average on an empty collection of non-nullable types throws "Sequence contains no elements". The MongoDB provider also does this.

      However, if the empty collection contains nullable types, and hence the return is also nullable, then L2O and EF Core providers return null. The MongoDB provider still throws in this case.

      using var context = new SomeDbContext();
      
      context.Database.EnsureDeleted();
      
      context.AddRange(new Order { OrderID = 1 });
      context.SaveChanges();
      
      var value = context.Set<Order>().Where(e => e.OrderID == -1).Average(e => (int?)e.OrderID);
      Console.WriteLine(value.HasValue ? value.Value : "<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>().ToCollection("Orders");
          }
      }
      
      public class Order
      {
          public int OrderID { get; set; }
      }
      

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

                Created:
                Updated: