我有一個查詢,我轉換爲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
有人可以幫助我在哪裏做錯了。
我最好的猜測是p.PaymentType或p.Currency是NULL – Ako 2015-02-24 16:00:07
@Ako是的,你是對的。讓我用一個樣本來解釋你。比如說貨幣USD的付款類型爲0,1而不是2。現在我的要求是我需要USD,2和金額的總和爲0.所以我在我的temp中創建了一個超集,然後嘗試加入它。所以現在對美元來說,2表中沒有數額,因此爲零。不知道如何處理它。 – user3182464 2015-02-24 16:36:17