c# – 轉換為值型別“Double”失敗,因為物化值為null
碼:
double cafeSales = db.InvoiceLines .Where(x => x.UserId == user.UserId && x.DateCharged >= dateStart && x.DateCharged <= dateEnd) .Sum(x => x.Quantity * x.Price);
錯誤:
轉換為值型別“Double”失敗,因為物化值為null.結果型別的通用引數或查詢必須使用可空型別.
我已經看到了什麼:
ofollow,noindex" target="_blank">The cast to value type ‘Int32’ failed because the materialized value is null
The cast to value type ‘Decimal’ failed because the materialized value is null
我有什麼:
double cafeSales = db.InvoiceLines .Where(x => x.UserId == user.UserId && x.DateCharged >= dateStart && x.DateCharged <= dateEnd) .DefaultIfEmpty() .Sum(x => x.Quantity * x.Price);
和:
double? cafeSales = db.InvoiceLines .Where(x => x.UserId == user.UserId && x.DateCharged >= dateStart && x.DateCharged <= dateEnd) .Sum(x => x.Quantity * x.Price);
這兩個都不工作.我知道這個問題的原因是該表中沒有對我進入的UserId的行.在這種情況下,我寧願Sum()剛剛返回一個0給我.有任何想法嗎?
double cafeSales = db.InvoiceLines .Where(x => x.UserId == user.UserId && x.DateCharged >= dateStart && x.DateCharged <= dateEnd) .Sum(x => (double?)(x.Quantity * x.Price)) ?? 0;
http://stackoverflow.com/questions/15297925/the-cast-to-value-type-double-failed-because-the-materialized-value-is-null