thi*_*rzy 6 c# linq entity-framework 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();
}
Run Code Online (Sandbox Code Playgroud)
我之前在 .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.
Run Code Online (Sandbox Code Playgroud)
内部异常更清晰:NULL REFERENCE EXCEPTION。
经过一些测试,我发现错误发生在 plan.Exercise 为空时,即使我试图通过首先检查它是否为空来避免异常。
如果我尝试直接在立即窗口中进行相同的检查,它应该返回“false”。
我在这里错过了什么吗?这可能是一个EF错误?例如,为什么这在 .NET 4.5 中有效,而在 .NET Core 2.0 中无效?
提前致谢。
更新
伊万的解决方案完成了这项工作:
重写?: 构造具有等价的 ||
plan.Excercise == null || plan.Exercise.Year <= 0 || e.Excercise.Year == plan.Exercise.Year
Run Code Online (Sandbox Code Playgroud)
如何将您的代码简化为类似的内容
public IEnumerable<Plan> GetPlans(int year)
{
return _context.Plans
.Where(e => e.Excercise.Year == year)
.ToList();
}
Run Code Online (Sandbox Code Playgroud)