使用LINQ查询比较日期 [英] Comparing dates in query using LINQ

查看:185
本文介绍了使用LINQ查询比较日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ查询,返回到一个变种类型myQry

I have a Linq query that returns to a var type myQry

var myQry = from .....

这是一个大的LINQ返回所有我需要进一步筛选记录。在我,如果条件我有运行像这样的检查对最新的过滤器。我需要检查,如果名称中包含输入的名字和出生日期完全匹配。

This is a large linq returns all the records that I need to filter further. In one of my if-conditions I have a filter that runs like this to check against date. I need to check if name contains the name entered and matches the birthdate exactly.

我想这里面编译和运行,但没有正常工作

I tried this which compiled and ran, but did not work correctly

myQry.Where(x => x.FirstName.Contains(strName) && DateTime.Compare( x.BirthDt, searchDt)>=0).ToList()

然后我想这这给抛出异常DbArithmeticEx pression参数必须有一​​个数字常见的类型

Then I tried this which gave threw an exception "DbArithmeticExpression arguments must have a numeric common type"

myQry.Where(x => x.FirstName.Contains(strName) && (x.BirthDt- searchDt).Days == 0).ToList();

对于此类的情况,当我使用where子句对我的查询,这将是做一个日期比较的最好方法是什么? LINQ查询的WHERE子句中不允许使用的是什么样的操作?

For such kind of a situation when I use a where clause on my query, what would be the best way to do a date comparison? What kind of operations are not allowed in the where clause of a LinQ query?

感谢您的时间...

推荐答案

在这种情况下,您可能需要使用方法从的 SqlMethods 类。

In this case you may want to use SQL Server specific functions using methods from the SqlMethods class.

你的第二个查询可以改写为

Your second query could be rewritten as

myQry.Where(x => x.FirstName.Contains(strName) && 
    SqlMethods.DateDiffDay(x.BirthDt, searchDt) == 0).ToList()

这将被转换为类似于

which will be translated to something like

SELECT ... FROM Table WHERE FirstName 
    LIKE '@p0' AND DATEDIFF(Day, BirthDt, @p1) = @p2

其中,p 0,p 1和p是参数。

where p0,p1 and p2 are parameters.

这篇关于使用LINQ查询比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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