1011 1110
1011 1110

Reputation: 781

Accepting a linq null

I have a linq query here that is done with entity framework. The query will return null every once in a while. So I had to write the linq query to accept this null. However this doesn't work. The if statement (viewsByUdHours != null) returns true then still executes the lines of code in the if statement.

       DateTime startDateTimeHours = now.AddHours(-24);

       var viewsByIdHours = db.ArticleViews
            .Where(av => av.ViewCreated >= startDateTimeHours)
            .GroupBy(av => av.ArticleID)
            .Select(g => new { ArticleID = g.Key, Count = g.Count() });

        if (viewsByIdHours != null)
        {
            var highestCountHours = viewsByIdHours.Max(v => v.Count);

            var topArticlesHours = viewsByIdHours.Where(a => a.Count == highestCountHours);

            var topArticleHours = topArticlesHours.First();

            var articleTitleHours = db.Articles.Where(x => x.ID == topArticleHours.ArticleID).Select(x => x.title).First();

            ViewBag.activityDay = articleTitleHours + " (" + topArticleHours.Count + ")";
        }
        else
            ViewBag.activityDay = "NaN";   

I get this error at the "var highestCountHours = viewsByIdHours.Max(v => v.Count);" line:

The cast to value type 'Int32' failed because the materialized value is null. 
Either the result type's generic parameter or the query must use a nullable type.

Upvotes: 0

Views: 72

Answers (2)

user3383479
user3383479

Reputation:

I hope it will help. As you have a null:

var viewsByIdHours = db.ArticleViews
        .Where(av => av.ViewCreated >= startDateTimeHours)
        .GroupBy(av => av.ArticleID)
        .Select(g => new { ArticleID = g.Key, Count = g.Count()??0 });

So if your field Count is null then it will be 0;

Upvotes: 0

kmacdonald
kmacdonald

Reputation: 3471

viewByIdHours will never be null. change your if statement to viewByIdHours.Any(). the variable viewByIdHours just holds the query and the query will never be null.

Upvotes: 3

Related Questions