如何仅显示SystemDate小于/大于存储日期的数据库记录?

如何仅显示SystemDate小于/大于存储日期的数据库记录?

问题描述:

我正在创建一个WPF C#应用程序,允许您添加,删除和编辑汽车租赁订单,我试图实现一项功能,只从数据库中选择完成的记录,或选择仍处于活动状态的记录。如何仅显示SystemDate小于/大于存储日期的数据库记录?

这是我excample ShowCompleted方法....

DateTime current = DateTime.Now; 
      var query = from CarRental in this.dbContext.CarRentals where (CarRental.Starting_Date.AddDays(CarRental.Duration)) < current select CarRental; 
      this.CarRentalViewSource.Source = query.ToList(); 

这是错误当我点击该按钮,我得到了,我不知道解决的办法是什么?

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll 

Additional information: LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression. 

任何帮助,将不胜感激

感谢

杰米·

+0

你是不是比较与存储的日期,你* *计算使用C#方法,'AddDays'它。这不能转换为SQL。这就是消息所说的 –

+1

另一个问题是,通过*计算*日期,即使您在SQL中这样做,您也可以防止服务器使用涵盖'Starting_Date'的任何索引。这将强制进行全表扫描。创建一个实际的或持久化的calcualted字段'Ending_Date'并将其添加到索引。 –

EntityFramework翻译所有功能sql,错误是说EntityFramework无法翻译DateTime.AddDays功能为sql。您需要使用DbFunctions.AddDays代替DateTime.AddDays,使你的代码看起来应该是这样

DateTime current = DateTime.Now; 
var query = from CarRental in this.dbContext.CarRentals where 
      (DbFunctions.AddDays(CarRental.Starting_Date, CarRental.Duration))) < current select CarRental; 
this.CarRentalViewSource.Source = query.ToList(); 
+1

即使*那*不是一个好主意,因为它阻止服务器使用涵盖'Startging_Date'字段的任何索引。这将工作,但导致全表扫描 –

+0

@PanagiotisKanavos是的,你是对的。但是我没有其他的方法可以解决这个问题。另一种解决方案是将已经计算的日期和查询存储在该列中,这在上面的注释中已经提到) –

+0

@Ruben,你确定这是最新的代码吗?它似乎产生更多的错误,而不是修复它们 –