我的 LINQ 中有一个方法 基本上,我的 LINQ 查询所做的是从我的数据库中检索数据。
用户可以在两个日期之间进行选择并检索这两个日期之间的数据。但是,如果用户选择的日期范围内没有数据,我会收到此错误:
The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type
即使没有数据,用户在两个日期之间搜索应该没问题,它应该给出一条错误消息,指出这些日期之间没有数据,而不是我在 Visual Studio 中收到的错误消息。 我首先使用 MVC Entity Framework 模型。
方法如下:
public List<CoreValueAndAverageGrade> GetAverageGradeForAllCoreValues(
OfficeStatisticQueryViewModel model)
{
var StartDate = DateTime.Parse(model.StartDate);
var EndDate = DateTime.Parse(model.EndDate);
return db.CoreValue
.Where(v => v.CoreValueQuestion
.Any(q => !q.SubjectType.Ignored_Statistic))
.Select(coreValue => new CoreValueAndAverageGrade
{
CoreValue = coreValue,
AverageGrade = coreValue.CoreValueQuestion
.Where(q => !q.SubjectType.Ignored_Statistic)
.Average(q => q.SelectedQuestions
.Where(s =>
s.GoalCardQuestionAnswer != null
&& s.GoalCardQuestionAnswer.Grade.HasValue
&& s.GoalCard.Completed_Date >= StartDate
&& s.GoalCard.Completed_Date <= EndDate
)
.Average(s => s.GoalCardQuestionAnswer.Grade.Value))
})
.ToList();
}
更新:Grade 是 Double
和 Nullable
非常感谢任何形式的帮助!
提前致谢!
最佳答案
查看查询的最后一部分 - 如果在使用 where
子句过滤后没有返回行,那么 s.GoalCardQuestionAnswer.Grade.Value
肯定会抛出因为您正在尝试访问空对象的属性。
我想如果您将代码更改为此,您将获得 0 作为最终值 - 然后您需要在代码中明确检查此值。
.Average(s => s != null ? s.GoalCardQuestionAnswer.Grade.Value : 0)
否则,分解查询将是一个好主意 - 它有助于代码的调试和可读性。
关于c# - 在我的存储库中使用 LINQ 的方法会出现空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10581356/