c# - LINQ:失败,因为物化值为 null

标签 c# linq

我试图在下面的代码中使用 sum 但出现错误:

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.

Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------

我在“let quantity”处收到错误

  var fullInfo = (from product in allProdcts
                 let quantity = db.Product_Order.Where(x=> x.ProductId == product.ID).Sum(x => x.Quantity)
                select new ReportVm
                    {                          
                        ProductId = product.ID,
                        ProductName = product.Name,
                        AmountProduct = quantity,
                        TotPrice = (quantity)*(product.Price)
                    }).ToList();

这是我的Product_Order 表(M-M 关系):

Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------

知道如何解决这个问题吗?

最佳答案

您需要允许可空的数量,您可以使用?? 表达式实现它并在使用 时转换为int? Sum().

.Sum(x => (int?)x.Quantity)??0

你的查询应该是这样的

var fullInfo = (from product in allProdcts
            let quantity = db.Product_Order.Where(x => x.ProductId == product.ID).Sum(x => (int?)x.Quantity)??0
            select new ReportVm
            {
                ProductId = product.ID,
                ProductName = product.Name,
                AmountProduct = quantity,
                TotPrice = (quantity)*(product.Price)
            }).ToList();

关于c# - LINQ:失败,因为物化值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439253/

相关文章:

c# - 用于过滤记录的 Entity Framework Linq 查询

c# - 如何加快此 LINQ 查询的速度?

c# - LINQ 性能常见问题

c# - 在局部 View mvc 中显示三篇随机文章

c# - 在连接字符串中设置到数据源的方式

c# - 使用 Windows Phone 8 NFC 读取 Mifare 标签?

c# - 将列表对象绑定(bind)到 javascript 数组

C# 如何检查数字是否更大?

c# - ef-core 加载嵌套 tph 继承成员的集合属性

c# - 联合身份 token 复制字符以关闭标签(cookie)(使用 Thinktecture Identity Server)