【发布时间】:2014-04-11 02:46:15
【问题描述】:
我在这里有一个使用实体框架完成的 linq 查询。查询将不时返回 null。所以我不得不编写 linq 查询来接受这个空值。但是,这不起作用。 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.
【问题讨论】:
-
viewByIdHours 永远不会为空。将您的 if 语句更改为
viewByIdHours.Any() -
np,变量 viewByIdHours 只保存查询(不确定确切的类型),查询永远不会为空。
标签: c# .net linq asp.net-mvc-4 linq-to-entities