2015-02-24 71 views
0

我有一个查询,我转换为LINQ表达式。但抛出空例外。sql到LINQ与左连接组和sum()抛出异常

目的:支付类型可以有三个值(0,1,2)。我需要为所有三种PaymentType查询所有货币的总额。另外,如果paymentType的三个值中的任何一个都不存在特定货币的记录。金额应该显示为零。

表结构:

 Currency varchar(10), 
     PaymentType(int), 
     amount(decimal) 

查询:

LINQ表达式:

 var temp = _db.Payments.Select(c => c.PaymentType) .Distinct() 
     .SelectMany(c => _db.Payments.Select(a => a.Currency).Distinct(), 
     (PaymentType, Currency) => new { PaymentType, Currency }).ToList(); 


     var data = from p in temp join c in _db.Payments on new {     
     p.PaymentType, p.Currency } equals new { c.PaymentType, c.Currency } 
     into j1 from j2 in j1.DefaultIfEmpty() group j2 by new { 
     p.PaymentType, p.Currency } into grouped select new { paymenttype = 
     grouped.Key.PaymentType, currency = grouped.Key.Currency, amount = 
     grouped.Sum(t => (decimal?)t.Amount ?? 0) }; 

但它给我的 “对象引用” 错误归因于的SelectMany声明NULL例外同时宣布新的。

  t => (decimal?)t.Amount ?? 0 

有人可以帮助我在哪里做错了。

+0

我最好的猜测是p.PaymentType或p.Currency是NULL – Ako 2015-02-24 16:00:07

+0

@Ako是的,你是对的。让我用一个样本来解释你。比如说货币USD的付款类型为0,1而不是2。现在我的要求是我需要USD,2和金额的总和为0.所以我在我的temp中创建了一个超集,然后尝试加入它。所以现在对美元来说,2表中没有数额,因此为零。不知道如何处理它。 – user3182464 2015-02-24 16:36:17

回答

0

我已经用一些示例数据重写了代码,并重现了所述的错误。

var Payments = new [] {new {PaymentType = 0, Currency = "EUR", Amount = 10}, 
           new {PaymentType = 0, Currency = "CHF", Amount = 70}, 
           new {PaymentType = 2, Currency = "CHF", Amount = 80}, 
           new {PaymentType = 1, Currency = "GBP", Amount = 90}, 
           new {PaymentType = 1, Currency = "EUR", Amount = 100}}; 


     var temp = Payments.Select(c => c.PaymentType).Distinct() 
          .SelectMany(c => Payments.Select(a => a.Currency).Distinct(), 
                  (pt, cur) => new { PaymentType = pt, Currency = cur }) 
          .ToList(); 


     var data = from p in temp 
        join c in Payments on new { p.PaymentType, p.Currency } equals new { c.PaymentType, c.Currency } into j1 
        from j2 in j1.DefaultIfEmpty() 
        group j2 by new 
        { 
         p.PaymentType, 
         p.Currency 
        } into grouped 
        select grouped; 

     foreach (var g in data.ToList()) 
     { 

      Console.WriteLine("{0},{1},{2}", g.Key.PaymentType, g.Key.Currency, g.Sum(t => t.Amount)); 
     } 


     Console.ReadLine(); 

所以问题是,t.amount不为null:t本身为空。所以你需要调整的是:

grouped.Sum(t => t == null ? 0 : t.Amount) 
+0

完美的工作:) – user3182464 2015-02-25 18:32:35