首页 > 解决方案 > 为什么 LINQ Sum() 抛出“System.Collections.Generic.KeyNotFoundException”?

问题描述

在这里我有

System.Collections.Generic.KeyNotFoundException:“字典中不存在给定的键“EmptyProjectionMember”。

var res = (from c in _context.Check
             join cp in _context.CheckProduct on c.Id equals cp.CheckId
             join p in _context.Product on cp.ProductId equals p.Id
             where c.Date.Date == date.Date
             select (cp.Quantity * Decimal.ToDouble(p.Price))).Sum();

但是当我写这个时,代码正在工作:

var res = (from c in _context.Check
             join cp in _context.CheckProduct on c.Id equals cp.CheckId
             join p in _context.Product on cp.ProductId equals p.Id
             where c.Date.Date == date.Date
             select (cp.Quantity * Decimal.ToDouble(p.Price)));
          
double sum = 0;          
foreach(var el in res)
{
   sum += el;
}

为什么 Sum() 不起作用?

标签: c#asp.netlinq

解决方案


尝试以下操作:

res = (from c in _context.Check
           join cp in _context.CheckProduct on c.Id equals cp.CheckId
           join p in _context.Product on cp.ProductId equals p.Id
           where c.Date.Date == date.Date
           select (cp.Quantity * Decimal.ToDouble(p.Price)))
          .DefaultIfEmpty(0)
          .Sum();

看起来没有什么可以选择的,所以在这种情况下,默认为 0。

在第二种情况下,您尝试迭代一个空的可枚举,因此它甚至不会进入 for each 子句。


推荐阅读