如何比较LINQ中的日期



我正在使用linq,我正在尝试比较两个日期,并且我得到的支持错误我搜索了它并使用了示例,但仍然遇到了不支持的错误- System.NotSupportedException,我在做什么错误?

//vars

int numDaysPassed =Int32.Parse(ConfigurationManager.AppSettings["DaysPassed"]);    
  DateTime todayPlusConfigDays = DateTime.Today.Date.AddDays(numDaysPassed);

//选项1

List<Customerfiles> Customerfiles = context.Customerfiles.Where(x => x.Status == currentStatus && (x.UpdateDate.Value.Date.CompareTo(todayPlusConfigDays)==0)).ToList<Customerfiles>();

//选项2

List<Customerfiles> Customerfiles = context.Customerfiles.Where(x => x.Status == currentStatus && (x.UpdateDate.Value.Date == todayPlusConfigDays)).ToList<Customerfiles>();

您遇到的错误是因为查询在数据库层中时,LINQ无法将您调用的每个函数转换为SQL中的类似调用,因为这些函数只是don't存在于sql。

为什么不进行简单的比较?

List<Customerfiles> Customerfiles = context.Customerfiles.Where(x => x.Status == currentStatus && x.UpdateDate.Value.Date == todayPlusConfigDays).ToList();

如果您想摆脱问题,而不必担心性能,请尝试以下操作:

List<Customerfiles> Customerfiles = context.Customerfiles.ToList().Where(x => x.Status == currentStatus && x.UpdateDate.Value.Date == todayPlusConfigDays).ToList();

我刚刚在查询开始时添加了一个" tolist(("。这将使所有客户文件进入内存,这通常是一种非常糟糕的方法。这样,Linq可以做任何您想要的事情,因为它不需要转换为SQL函数。

最新更新