LINQ:失败,因为具体化值为null

fag*_*gol 5 c# linq

我正在尝试在下面的代码中使用sum但我收到错误:

转换为值类型'System.Int32'失败,因为实现的值为null.结果类型的泛型参数或查询必须使用可空类型.

Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------
Run Code Online (Sandbox Code Playgroud)

我收到错误" 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();
Run Code Online (Sandbox Code Playgroud)

这是我的Product_Order表(MM关系):

Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------
Run Code Online (Sandbox Code Playgroud)

不知道怎么解决这个问题?

M. *_*cki 11

你需要允许一个可空Quantity,你可以使用??表达式实现它并int?在你使用时强制转换Sum().

.Sum(x => (int?)x.Quantity)??0
Run Code Online (Sandbox Code Playgroud)

您的查询应该是这样的

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();
Run Code Online (Sandbox Code Playgroud)