DatabaseDataContext db = new DatabaseDataContext();
var TMACost = (from emp in db.Incomes where emp.Time > DateTime.Today.AddMonths(-1) select emp.Cost).Sum();
Label15.Text = TMACost.ToString();
我想在数据库中求值,但是当数据库为空时无法运行,任何想法?
答案 0 :(得分:0)
使用强制转换为可空数字。当表为空时,这将返回null。然后,您可以使用coalesce运算符:
var TMACost = (
from emp in db.Incomes
where emp.Time > DateTime.Today.AddMonths(-1)
select (decimal?) emp.Cost
).Sum() ?? 0m;
答案 1 :(得分:-1)
你试图对可能返回null的值求和,所以在求和之前检查它是否为null
DatabaseDataContext db = new DatabaseDataContext();
var TMACost = (from emp in db.Incomes where emp.Time > DateTime.Today.AddMonths(-1) select emp.Cost);
Label15.Text = (TMACost.length!=DBNull.Value)?TMACost.Sum().ToString():"0";