Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当我尝试按DateTime排序时,为什么我的Linq查询抛出异常?_C#_Linq - Fatal编程技术网

C# 当我尝试按DateTime排序时,为什么我的Linq查询抛出异常?

C# 当我尝试按DateTime排序时,为什么我的Linq查询抛出异常?,c#,linq,C#,Linq,我有这个方法,就是要过滤我的博客条目每月 public IList<KeyValuePair<string, int>> GetBlogsByMonth(PteDotNetCore.EnumsAndConstants.BlogType blogTypeArg) { var blogsOfType = from b in dataContext.blogs where b.

我有这个方法,就是要过滤我的博客条目每月

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;

        }
Blog是一个实体框架对象。老实说,我有点困惑,为什么我必须查看blog.DateTime对象的值。即使我把它改成

var blogsInMonth = from b in blogsOfType
                                   where ((DateTime)b.DateAdded).Month == DateTime.Now.AddMonths(-i).Month
                                   select b;

它仍然不起作用…希望有人能帮助…

最有可能的是
博客。DateAdded
列在数据库中可以为null,并且该列中存在null值

你可以试试

where b.DateAdded != null && ((DateTime)b.DateAdded).Month == DateTime.Now.AddMonths(-i).Month

我想这是因为你的
b.DateAdded
是空的。尝试更改顶部的行,如下所示:

var blogsOfType = from b in dataContext.blogs
    where b.DateAdded != null && b.BlogType == (int)blogTypeArg
    select b;

作为优化问题,您可以在Linq表达式之外计算“i moths back”。如果有很多博客条目,你就不会做比需要更多的
DateTime.Now.AddMonth(-1)

DateAdded
a
DateTime?
null
)吗?如果是这样的话,那么这表明其中一个
DateAdded
对象是空的,而不是包含一个值,您应该首先检查空值。好的,这是可行的,但是我的数据中没有任何空值?
var blogsOfType = from b in dataContext.blogs
    where b.DateAdded != null && b.BlogType == (int)blogTypeArg
    select b;