[英]Why does my Linq query throw an exception when I try and sort on DateTime?
I have this method that is meant to filter my blog entries by month... 我有这个方法,用于按月过滤我的博客条目...
public IList<KeyValuePair<string, int>> GetBlogsByMonth(PteDotNetCore.EnumsAndConstants.BlogType blogTypeArg)
{
var blogsOfType = from b in dataContext.blogs
where b.BlogType == (int)blogTypeArg
select b;
IList<KeyValuePair<string, int>> retVal = new List<KeyValuePair<string, int>>();
for(int i= 12; i > 1; i--)
{
var blogsInMonth = from b in blogsOfType
where ((DateTime)b.DateAdded).Month == DateTime.Now.AddMonths(-i).Month
select b;
KeyValuePair<string, int> keyToAdd = new KeyValuePair<string, int>(DateTime.Now.AddMonths(-i).Month.ToString(), blogsInMonth.ToList().Count);
retVal.Add(keyToAdd);
}
return retVal;
}
When I use the debugger blogsInMonth I get an error 当我使用调试器blogsInMonth时,我收到一个错误
base {System.SystemException} = {"Nullable object must have a value."}
Blog is an entity framework object. 博客是一个实体框架对象。 To be honest Im a bit confused as to why I have to look in the Value of the blog.DateTime object.
说实话我有点困惑为什么我要查看blog.DateTime对象的值。 Even when I change it to...
即使我把它改成......
var blogsInMonth = from b in blogsOfType
where ((DateTime)b.DateAdded).Month == DateTime.Now.AddMonths(-i).Month
select b;
It still doesnt work...Hope someone can help... 它仍然无法工作...希望有人可以帮助......
Most likely the Blog.DateAdded
column is nullable in the database and there exists null values in the column. 很可能
Blog.DateAdded
列在数据库中可以为空,并且列中存在空值。
You can try 你可以试试
where b.DateAdded != null && ((DateTime)b.DateAdded).Month == DateTime.Now.AddMonths(-i).Month
I think this is because your b.DateAdded
is null. 我认为这是因为你的
b.DateAdded
为null。 Try changing the lines at the top as follows: 尝试更改顶部的行,如下所示:
var blogsOfType = from b in dataContext.blogs
where b.DateAdded != null && b.BlogType == (int)blogTypeArg
select b;
As a matter of optimization, you can calculate "i moths back" outside of your Linq expression. 作为优化问题,您可以在Linq表达式之外计算“i moths back”。 In case there are many blog entries, you wouldn't be doing
DateTime.Now.AddMonth(-1)
more times than necessary. 如果有许多博客条目,您将不会比必要时多做
DateTime.Now.AddMonth(-1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.