简体   繁体   English

尽管 SingleOrDefault() 会返回 null,但 EF Core LINQ 查询何时导致 null 合并?

[英]When does EF Core LINQ query result in null coalescing despite SingleOrDefault() would return null?

I have a query against the DbContext something like:我有一个针对 DbContext 的查询,例如:

ctx.Items.SingleOrDefault(i => i.Id == *someQueryThatReturns0*).Code

The someQueryThatReturns0 is a query that looks up an Id, something like the following: someQueryThatReturns0是一个查找 Id 的查询,如下所示:

otherItems.Where(h => h.Id == xyz).Select(s => s.OtherId).SingleOrDefault()

When this inner query has no results, then the inner SingleOrDefault will return 0 because the Ids are int, and this means the outer Items.SingleOrDefault(..) should result in null.当这个内部查询没有结果时,内部SingleOrDefault将返回 0,因为 Id 是 int,这意味着外部Items.SingleOrDefault(..)应该导致 null。

But when referencing Items.SingleOrDefault(..).Code instead of getting NullRef exception, it will be just null.但是当引用Items.SingleOrDefault(..).Code而不是得到 NullRef 异常时,它将只是 null。

This whole thing is part of a bigger query where it is used in to set values in a Select(), something like:这整个事情是一个更大的查询的一部分,它用于在 Select() 中设置值,例如:

someComplexQuery.Select(x => new someDto(){
  ...
  someProp = x.Valid ? ctx.Items.SingleOrDefault(i => i.Id == *someQueryThatReturns0*).Code : null;
  ...
})

When executing the query I would have expected a NullRef exception, but instead someProp is simply coalesced to null basically.执行查询时,我会期待 NullRef 异常,但 someProp 基本上只是简单地合并到null Is this the expected behavior simply because referencing .Code in the query like this will be translated into the SQL query somehow?这是预期的行为,仅仅是因为在这样的查询中引用.Code会以某种方式转换为 SQL 查询吗? Or am I missing something here?或者我在这里错过了什么?

  someProp = x.Valid ? ctx.Items.SingleOrDefault(i => i.Id == *someQueryThatReturns0*).Code : null;

This line should definitely return null at the SingleOrDefault, if Item object is a class, and therefore to throw NullReferenceException.如果项目 object 是 class,则此行肯定会在 SingleOrDefault 处返回 null,因此抛出 NullReferenceException。

If it's a struct type then it would initialize the struct with all its values in turn default initialized (ie zero, null, etc.).如果它是一个结构类型,那么它将初始化结构,其所有值依次默认初始化(即零、null 等)。

Assuming it's a class, the only way that someProp will be set to null eventually, is if Items collection has an item with Id equal to zero, and it's Code property is set to null , or if x.Valid is set to false .假设它是 class,最终将someProp设置为null的唯一方法是,如果 Items 集合有一个 Id 等于 0 的项目,并且它的Code属性设置为null设置为false ,或者如果x.Valid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM