I have a simple model with two entities:
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(150)] public string Name { get; set; }
}
public class Order
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public decimal? Amount { get; set; }
public int? ProductId { get; set; }
[ForeignKey(nameof(ProductId))] public Product Product { get; set; }
}
public class OrderContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
As you see, There is a nullable foreign key between the Order
and Product
.
I initialized the DB with these records:
using (var db = new OrderContext())
{
var p = new Product {Name = "Test"};
db.Products.Add(p);
db.Orders.Add(new Order {Product = p, Amount = 1});
db.Orders.Add(new Order {ProductId = null, Amount = 2});
db.SaveChanges();
}
When I execute the following query, an InvalidOperationException
is raised:
var result = db.Orders.GroupBy(x => x.Product.Id).ToArray();
The exception message is:
System.InvalidOperationException: The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
Is this a bug in EF and how to resolve it?
--
This is not duplicate of The cast to value type 'Int32' failed because the materialized value is null . Despite of the same exception message, the causes and solutions of the problems are completely different. The referred question is about aggregating an empty collection. But this is about grouping by the primary key of another left-joined table. I don't know why should these two questions be even similar!