EF中的LINQ在搜索空值时失败
本文关键字:空值 失败 搜索 中的 LINQ EF | 更新日期: 2023-09-27 18:28:10
我有以下代码。
//I pick the first story where its StartSegment is not null.
var story = container.StorySet.FirstOrDefault(s => s.StartSegment != null);
if (story != null)
{
//the following assert fails because story.StartSegment is null.
Assert.IsNotNull(story.StartSegment,
"The target story of this homework has no start segment.");
}
这个单元测试失败了,因为故事。StartSegment实际上是null,但考虑到FirstOrDefault lambda表达式显式搜索起始段不为null的故事,我认为这没有任何意义。
有人能帮我吗?
这是一个懒惰/急于加载的问题。
事实上Story.StartSegment不为null。
但你没有(急切地)把它包括在内。试试这个。。
var story = container.StorySet
.Include("StartSegment ")
.FirstOrDefault(s => s.StartSegment != null);
假设你的实体关系是这样的。。
故事集(多个)-----(0或1)开始段
StartSegment定义为StorySet的"NavigationProperty"。并且您生成的查询看起来像
SELECT * FROM StorySet WHERE StorySet.StartSegmentId is not null
此查询返回一些现有实体,但默认情况下,EF不会创建导航属性的即时消息,除非您明确告诉它。Include("StartSegment")
尝试以下代码:
var story = container.StorySet.Where(s => s.StartSegment != null).FirstOrDefault();
我认为这是DB布尔逻辑相关的问题。在SQL中,这不是真的:someNullValue = NULL
。相反,您应该使用someNullValue IS NULL
。在这种情况下,EF可能不关心正确的null比较,所以它只返回第一个元素,该元素可能具有null StartSegment
。请检查已向数据库发出的查询。它应该有IS NULL
谓词,而不是类似= NULL
的东西