Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
可为Null的对象必须具有linq to sql查询的值_Linq_Linq To Sql - Fatal编程技术网

可为Null的对象必须具有linq to sql查询的值

可为Null的对象必须具有linq to sql查询的值,linq,linq-to-sql,Linq,Linq To Sql,我有下面的linq查询,如果预算没有任何类别,它会抛出一个错误。我做错什么了吗?如果没有类别,我可以将sum设置为返回0吗?我对linqtosql相当陌生 var r = from rec in DbContext.budgets where rec.budgetID == updatedBudget.budgetID select new { rec.budgetID, rec.totalInco

我有下面的linq查询,如果预算没有任何类别,它会抛出一个错误。我做错什么了吗?如果没有类别,我可以将sum设置为返回0吗?我对linqtosql相当陌生

var r = from rec in DbContext.budgets
        where rec.budgetID == updatedBudget.budgetID
        select new
        { 
            rec.budgetID,
            rec.totalIncome,
            totalSpent = rec.categories.Sum(a => a.amount)
        };

return new JsonResult(r.FirstOrDefault(), JsonSettings);
你可以试试这个

var r = from rec in DbContext.budgets
        where rec.budgetID == updatedBudget.budgetID
        select new
        { 
            rec.budgetID,
            rec.totalIncome,
            totalSpent = rec.categories != null ? rec.categories.Sum(a => a.amount) : 0
        };

return new JsonResult(r.FirstOrDefault(), JsonSettings);

我已经重新格式化了代码,这样我们可以很容易地一次看到所有代码。如果您特别想要以前的格式,当然可以随意还原。(不幸的是,我对LINQ to SQL的了解不够,无法给出答案。)您能否显示堆栈跟踪,以便我们确切地知道有什么问题?类别的类型是什么?您正在使用EF吗?如果是,使用什么版本?