我试图在下面的代码中使用 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/