简体   繁体   English

linq-to-sql SingleOrDefault返回null

[英]linq-to-sql SingleOrDefault return when null

I'm writing a linq-to-sql query and I'm loading an ID (a bigint in the database and a long in my code) from a table, something like this: 我正在编写一个linq-to-sql查询,并且正在从一个表中加载一个ID(数据库中的bigint和我的代码中的long bigint ),如下所示:

var SomeQuery = (from x in ...
                 select x.ID).SingleOrDefault();

When I get the result, I use SingleOrDefault in case the return is empty. 得到结果后,如果返回为空,则使用SingleOrDefault Does that mean that if the result is empty the SomeQuery variable will be 0 or null? 这是否意味着如果结果为空,则SomeQuery变量将为0还是null?

Thanks. 谢谢。

If you look the documenation for SingleOrDefault 如果您查看SingleOrDefault的文档

Returns the only element of a sequence, or a default value if the sequence is empty; 返回序列的唯一元素;如果序列为空,则返回默认值;否则,返回默认值。 this method throws an exception if there is more than one element in the sequence. 如果序列中有多个元素,则此方法将引发异常。

It cleary states that if the sequence is empty it will return the default value which for long and bigint is 0 . 明确指出,如果序列为空,则将返回默认值 ,long和bigint的默认值为 0 Why explained below 为什么在下面解释

Documenation for default keyword states 默认关键字状态的文档

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance: 在泛型类和方法中,出现的一个问题是,当您事先不了解以下内容时,如何将默认值分配给参数化类型T:

Whether T will be a reference type or a value type. T是引用类型还是值类型。

If T is a value type, whether it will be a numeric value or a struct. 如果T是值类型,则它是数字值还是结构。

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. 给定参数化类型T的变量t,语句t = null仅在T是引用类型且t = 0仅适用于数值类型而不适用于结构的情况下才有效。 The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. 解决方案是使用默认关键字,对于引用类型,该关键字将返回null,对于数值类型,将返回

Default is returned if no element found.(default value of int is 0) 如果未找到任何元素,则返回默认值。(int的默认值为0)

Value is returned if one is found. 如果找到一个,则返回值。

Exception is thrown if more than one is found. 如果发现多个,则抛出异常。

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

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