Reputation: 1373
What are the possible reasons for .FirstOrDefault()
to return null if a collection has at least one item? This is using Sitefinity and the videos manager is built into the CMS.
Code:
protected virtual Video GetVideo(Guid id)
{
LibrariesManager librariesManager = LibrariesManager.GetManager();
IQueryable<Video> videos = librariesManager.GetVideos(); // Five Items
IQueryable<Video> x = videos.Where(d => d.Id == id); // Correctly filters to one item with the matching Id
Video video = x.FirstOrDefault(); // null
if (video != null)
{
video = librariesManager.Lifecycle.GetLive(video) as Video;
}
return video; // <- Breakpoint is set here.
}
I've have also tried simply using .First()
as well as converting it into a List and taking the first index using x[0]
. The collection has an item each time, but video is always null;
For the record, I am following this guide, and split the query into multiple variables to see what's going on at each step.
Edit:
To clarify, videos
itself is a collection of five items and the .Where
correctly filters to the single item matching the Id
, which then gets assigned to x
. Video video = x.FirstOrDefault();
is the first instance where the actual result is different from the expected.
Upvotes: 1
Views: 960
Reputation: 62308
You reassign video
in the if
block if it is not null. With that re-assignment you are also casting the result. Both of those could be reasons why video
is null when you hit your break point.
librariesManager.Lifecycle.GetLive(video)
<- could return a null
valuelibrariesManager.Lifecycle.GetLive(video)
could return an instance that cannot be cast to Video
which would result in a null
value being assigned.if (video != null) // so not null here
{
video = librariesManager.Lifecycle.GetLive(video) as Video;
}
return video; // <- Breakpoint is set here.
I am thinking you have your if
statement's null
check backwards (check for null instead of not null) but that is a guess as we don't know what Lifecycle.GetLive
actually does.
Upvotes: 3
Reputation: 44
try use this
var videos = LibraryManager.GetVideos();
var video = videos.where(d => d.id == id).FirstOrDefault();
Upvotes: 0