c# - 在我的存储库中使用 LINQ 的方法会出现空错误

标签 c# asp.net-mvc asp.net-mvc-3 linq entity-framework

我的 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/

相关文章:

c# - 如何制作表格中心的面板?

c# - 组合 `using` 语句与一个一个地执行它们一样吗?

c# - Breeze js-如何添加新的子实体并将其附加到父级的子实体集合

c# - 如何正确获取Json值?

asp.net-mvc-3 - MVC3下拉列表未选择所选项目

asp.net-mvc - 远程验证似乎有问题

c# - ASP.NET Core API 发送用双引号引起来的字符串

c# - 我无法获得我在 Controller 中发布的文本框中的值

mysql - 导入 csv 和 xls 以批量上传用户以在网站中注册

asp.net-mvc - 如何将 Orchard CMS 与当前的 MVC2 应用程序集成?