问题描述
我正在尝试通过 MVC 5/Entity Framework 6 应用程序中的 Linq 表达式使用 DateDiff SQL 语法获取今天添加的所有记录.DateDiff 函数抛出运行时错误
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
其实我想用 linq 动态解析下面的 linq WHERE 子句
Actually i want to the following linq WHERE clause to parse with linq dynamics
.Where(p => DbFunctions.DiffDays(p.added_date, DateTime.Now) == 0)
为了获取今天添加的记录.我正在使用的示例代码如下所示
in order to fetch today added records. Sample code that i am using shown below
var _list = new vsk_error_log();
using (var entities = new vskdbEntities())
{
_list = entities.vsk_error_log
//.Where("DateDiff(DAY,added_date,getdate())=0")
.Where(p => DbFunctions.DiffDays(p.added_date, DateTime.Now) == 0)
.ToList();
}
return _list;
关于 Linq.Dynamic 表达式 - 如何编写 where 子句
Regarding Linq.Dynamic Expressions - how to write where clause
LINQ 中的动态 WHERE 子句
推荐答案
使用DbFunctions
.Where(p => DbFunctions.DiffDays(p.AddedDate, DateTime.Now) == 0)
如果您想动态调用它,您需要修改动态 LINQ 的代码.
If you want to invoke this dynamically, you'll need to modify code for the Dynamic LINQ.
- 下载 包含 DynamicLibrary.cs 的示例项目.该文件位于 App_Code 文件夹下.
- 找到
predefinedTypes
的静态定义并在最后添加typeof(DbFunctions)
.
- Download the sample project containing DynamicLibrary.cs. The file is located under App_Code folder.
- Find the static definition for
predefinedTypes
and addtypeof(DbFunctions)
at the very end.
现在你可以这样做了:
.Where("DbFunctions.DiffDays(AddedDate, DateTime.Now) = 0")
它会被翻译成这个SQL:
And it will be translated to this SQL:
WHERE 0 = (DATEDIFF (day, [Extent1].[AddedDate], SysDateTime()))
这篇关于使用带有 Linq.Dynamic 库的 DateDiff 来获取今天的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!