接受linq null

时间:2014-04-11 02:46:16

标签: c# .net linq asp.net-mvc-4 linq-to-entities

我在这里有一个linq查询,它是用实体框架完成的。该查询将偶尔返回null。所以我不得不编写linq查询来接受这个null。然而,这不起作用。 if语句(viewsByUdHours!= null)返回true,然后仍然在if语句中执行代码行。

       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";   

我在" var highestCountHours = viewsByIdHours.Max(v => v.Count);"行:

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.

2 个答案:

答案 0 :(得分:3)

viewByIdHours永远不会为空。将您的if语句更改为viewByIdHours.Any()。变量viewByIdHours只保存查询,查询永远不会为空。

答案 1 :(得分:0)

我希望它会有所帮助。因为你有一个null:

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

因此,如果您的字段Count为null,则它将为0;