c# - EF LINQ 查询 if 子句中抛出空引用异常

标签 c# entity-framework linq asp.net-web-api .net-core

我找不到确切的词来解释发生的事情,所以如果这是一个重复的问题,我深表歉意。

我尝试在 LINQ 查询中执行一个非常简单的 AND 条件 if 子句,以检查对象是否为空,然后验证其属性是否等于我想要比较的列。

代码:

public IEnumerable<Plan> GetPlans(Plan plan)
    {
        return _context.Plans.Where(e =>
            e.Situation == plan.Situation &&
            e.Notes.Contains(plan.Notes) &&
            (plan.Excercise != null && plan.Exercise.Year > 0 ? e.Exercise.Year == plan.Exercise.Year: true)).ToList();
    }

我已经在 .NET 4.5 中做过十几次这种检查,没有遇到任何问题。

但是现在,在我正在处理的第一个 .NET Core 2.0 项目中,我遇到了以下错误:

An exception was thrown while attempting to evaluate a LINQ query parameter expression. To show additional information call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.

内部异常更清晰:NULL REFERENCE EXCEPTION

经过一些测试,我发现错误发生在 plan.Exercise 为 null 时,即使我试图通过首先检查它是否为 null 来避免异常。

如果我尝试直接在立即窗口中进行相同的检查,它会返回“false”,这是应该的。

我是不是漏掉了什么?这可能是一个 EF 错误?例如,这在 .NET 4.5 中有效而不在 .NET Core 2.0 中有效的任何特定原因?

提前致谢。

更新

Ivan 的解决方案完成了这项工作:

重写? : 用等效的 ||

构造
plan.Excercise == null || plan.Exercise.Year <= 0 || e.Excercise.Year == plan.Exercise.Year

最佳答案

听起来这可能是 EF Core 中的错误(但我不确定)。

如果未满足 plan 的基本要求,您可能会尝试快速失败,更重要的是,不要使用三元运算符,而是使用传统的比较运算符和括号:

public IEnumerable<Plan> GetPlans(Plan plan)
{
    if (plan == null) return new List<Plan>();

    return _context.Plans
        .Where(e =>
            e.Situation == plan.Situation &&
            e.Notes.Contains(plan.Notes) &&
            (plan.Exercise == null || 
            plan.Exercise.Year <= 0 || 
            e.Excercise.Year == plan.Exercise.Year))
        .ToList();
}

关于c# - EF LINQ 查询 if 子句中抛出空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48157183/

相关文章:

c# - 无法在 asp vNext 中修改 HttpResponse 对象上的原因短语

c# - 行过滤器中的多个参数

c# - 如果 model 为 null ,如何处理 null 异常,如何在 mvc 的 View 中处理它?

c# - EF upsert 是否必须手动完成?

c# - Linq.Except的更多 "SQL-syntax"

c# - Screen.AllScreen 未提供正确的显示器计数

javascript - 语法错误: Unexpected token in JSON at position 0

c# - 使 Linq 导航属性对开发人员来说更加明显

java - scala -> 在同一程序中使用 .net (linq) 和 java 代码库?

c# - 将 int 上的无效转换异常加倍