2015-02-24 41 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