Reputation: 15886
I have the following code.
//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.");
}
This unit-test fails, because story.StartSegment is in fact null, but given the FirstOrDefault lambda expression which explicitly searches for stories where the start segment isn't null, I don't think this makes any sense.
Can anyone help me?
Upvotes: 0
Views: 980
Reputation: 11
Try the following code:
var story = container.StorySet.Where(s => s.StartSegment != null).FirstOrDefault();
Upvotes: 1
Reputation: 3939
it's lazy/eager load ploblem.
in fact Story.StartSegment is not null.
but you didn't include it (by eager load). try this..
var story = container.StorySet
.Include("StartSegment ")
.FirstOrDefault(s => s.StartSegment != null);
assume that your entitie relation like this..
StorySet (many) ----- (0 or 1) StartSegment
StartSegment defined as "NavigationProperty" of StorySet. and your generated query look like
SELECT * FROM StorySet WHERE StorySet.StartSegmentId is not null
this query return some existing entity. but by default EF will not create instant of Navigation Property until you explicitly tell it to .Include("StartSegment")
Upvotes: 3
Reputation: 17274
I think it's DB bool logic related issue. In SQL this is not true: someNullValue = NULL
. Instead you should use someNullValue IS NULL
. Probably EF doesn't care about correct null comparison in this case, so it just returns the first element, which might have null StartSegment
. Check the query that it is issued to the database. It should have IS NULL
predicate, not something like = NULL
Upvotes: 0