Using DateDiff with Linq.Dynamic library for fetching today records

后端 未结 6 985
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 16:23

I am trying to fetch all records added today using DateDiff SQL syntax via Linq expression in MVC 5 / Entity Framework 6 application. DateDiff function throw runtime error

6条回答
  •  [愿得一人]
    2020-12-10 17:11

    Use DbFunctions

    .Where(p => DbFunctions.DiffDays(p.AddedDate, DateTime.Now) == 0)
    

    Edit:

    If you want to invoke this dynamically, you'll need to modify code for the Dynamic LINQ.

    1. Download the sample project containing DynamicLibrary.cs. The file is located under App_Code folder.
    2. Find the static definition for predefinedTypes and add typeof(DbFunctions) at the very end.

    Now you will be able to do this:

    .Where("DbFunctions.DiffDays(AddedDate, DateTime.Now) = 0")
    

    And it will be translated to this SQL:

    WHERE 0 = (DATEDIFF (day, [Extent1].[AddedDate], SysDateTime()))
    

提交回复
热议问题