【发布时间】:2021-04-09 18:58:03
【问题描述】:
我想了解为什么我的代码会引发空引用异常。
DisruptionReportSteps 不为空,问题不在他们身上。我的猜测是,通过抛出 nre,EF 告诉它不能将我的布尔值投影到列表中,因为它不可能处理原始类型的集合。我说的对吗?
var disruptionReportsQuery = _dbContext.Reports
// query
.Select(report => new
{
AreStepsFilled = new List<bool>
{
report.DisruptionReportFirstStep.IsFilled,
report.DisruptionReportSecondStep.IsFilled,
report.DisruptionReportThirdStep.IsFilled,
report.DisruptionReportFourthStep.IsFilled,
report.DisruptionReportFifthStep.IsFilled,
},
})
如果我这样做:
var disruptionReportsQuery = _dbContext.Reports
// query
.Select(report => new
{
IsFirstStepFilled = report.DisruptionReportFirstStep.IsFilled,
IsSecondStepFilled = report.DisruptionReportSecondStep.IsFilled,
IsThirdStepFilled = report.DisruptionReportThirdStep.IsFilled,
IsFourthStepFilled = report.DisruptionReportFourthStep.IsFilled,
IsFifthStepFilled = report.DisruptionReportFifthStep.IsFilled,
})
它有效。
不过,我想确保我理解为什么会出现这种行为。
【问题讨论】:
-
你用的是什么版本的ef?
-
实体框架核心 3.1.4
-
我对各种 EF 核心版本(3 和 5)做了完全相同的事情,我可以毫无问题地执行与您的第一个类似的查询。如果查询表达式抛出 NRE,它通常表示翻译逻辑中存在错误,因为在 C# 代码中实际上没有计算任何值。这将有助于了解更多详细信息,例如堆栈跟踪和数据库提供程序(查询提供程序)以深入了解。答案中的解决方法无助于理解。
-
@GertArnold 很抱歉,它是 3.1 EF。翻译没有太大问题。它从数据库中获取所有记录而没有任何警告,并在此之后对其进行转换。它将是 EF 5 ,它会给出一个翻译错误,因为它的工作方式不同并尝试将查询转换为 SQL。
-
@GertArnold,我正在使用 Npgsql.EntityFrameworkCore.PostgreSQL 3.1.4。我认为谢尔盖的解释是理所当然的......
标签: c# select .net-core entity-framework-core nullreferenceexception