Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 可为空的Linq表达式_C#_Linq_Linq To Entities - Fatal编程技术网

C# 可为空的Linq表达式

C# 可为空的Linq表达式,c#,linq,linq-to-entities,C#,Linq,Linq To Entities,这个问题看起来很愚蠢,但我就是不明白。 我的实体: public class Page { public int Id { get; set; } //... public int? ParentId { get; set; } } 在控制器中: db.Pages.First(x => x.ParentId == null); 按预期工作(返回某些元素)。 但是: 抛出序列不包含任何元素 我错过了什么?我相信在一些LINQ提供程序中,空值有一个奇怪的地方。尝试:

这个问题看起来很愚蠢,但我就是不明白。 我的实体:

public class Page
{
    public int Id { get; set; }
    //...
    public int? ParentId { get; set; }
}
在控制器中:

db.Pages.First(x => x.ParentId == null);
按预期工作(返回某些元素)。 但是:

抛出
序列不包含任何元素


我错过了什么?

我相信在一些LINQ提供程序中,空值有一个奇怪的地方。尝试:

var query = db.Pages.First(x => (test != null && x.ParentId == test) ||
                                (test == null && x.ParentId == null));
或者,针对不同的情况使用不同的查询:

var query = test == null ? db.Pages.First(x => x.ParentId == null)
                         : db.Pages.First(x => x.ParentId == test);
基本上这是因为SQL将NULL视为与自身不相等,因此:

WHERE X = Y
如果X和Y都是空值,则仍将失败。使用
==null
部分(带有文本null)强制转换为
ISNULL
或任何与SQL等价的内容

我同意这是一种痛苦,其他人可能有更好的解决办法,但这可能有助于你开始工作。

试试这个(根据格多龙的评论进行修改。现在这正是吉迪恩发布的内容,所以请接受他的,而不是我的):


您可以这样做作为解决方法:

int? test = null;
if(test.HasValue) {
 db.Pages.First(x => x.ParentId == test.Value);
} else {
 db.Pages.First(x => x.ParentId == null);
}

我假设,因为
int?
实际上是一个
可为空的
我们的linq to entities提供程序没有正确比较事物。

您使用linq to entities吗?这与asp.NETMVC?没有任何特定关系。它将不起作用<代码>值-如果HasValue属性为true,则当前可为null(of T)对象的值。=>如果HasValue属性为false,则引发异常。这个解决方案的thx,但我只是想了解LINQ的奇怪之处
int? test = null;
if(test.HasValue) {
    db.Pages.First(x => x.ParentId == test.Value);
} else {
    db.Pages.First(x => x.ParentId == null);
}
int? test = null;
if(test.HasValue) {
 db.Pages.First(x => x.ParentId == test.Value);
} else {
 db.Pages.First(x => x.ParentId == null);
}