Quangdao Nguyen
Quangdao Nguyen

Reputation: 1373

.FirstOrDefault() is returning null on a non-empty IQueryable

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.
    }

Result for x: Result for x

Result for video: Result for video

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

Answers (2)

Igor
Igor

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 value
  • The result from librariesManager.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

Haady Baabs
Haady Baabs

Reputation: 44

  1. First check the videos list have one item that is exactly your item ( with d.Id is exactly that parameter id)
  2. try use this

    var videos = LibraryManager.GetVideos();
    var video  = videos.where(d => d.id == id).FirstOrDefault();
    

Upvotes: 0

Related Questions