使用DateDiff与Linq.Dynamic库提取今天的记录 [英] Using DateDiff with Linq.Dynamic library for fetching today records

查看:162
本文介绍了使用DateDiff与Linq.Dynamic库提取今天的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过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 WHERE子句来解析linq动态

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)

编辑

如果您想动态调用此类,您需要修改Dynamic LINQ的代码。

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


  1. 下载包含DynamicLibrary.cs的示例项目。该文件位于App_Code文件夹下。

  2. 找到 presetTypes 的静态定义,并添加 typeof(DbFunctions) 在最后。

  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.

现在你可以这样做:

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

它将被翻译成这个SQL:

And it will be translated to this SQL:

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

这篇关于使用DateDiff与Linq.Dynamic库提取今天的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆