简体   繁体   English

LINQ中的DateTime比较未返回正确的结果

[英]DateTime comparison in LINQ not returning correct results

I have the following LINQ to query the database and retreive deleted products from a particular date. 我有以下LINQ来查询数据库并从特定日期检索已删除的产品。

 return _myDbEntities.Log
            .Where(p => p.Action.Equals("Deleted") &&
            (p.ActionDate > fromDate))
            .Select(p => new DeletedProduct()
            {
                ProductId = p.ProductId,
                ActionDate = p.ActionDate
            }).ToList();

However, the query is retreiving values like product.ActionDate.Value = {12/8/2016 11:41:00 AM} when the fromDate was fromDate = {12/8/2016 11:41:00 AM} 但是,当fromDate来自日期= {12/8/2016 11:41:00 AM}时,查询正在检索诸如product.ActionDate.Value = {12/8/2016 11:41:00 AM}之类的值。

The query clearly says GREATER THAN. 查询清楚地说大于。 What is happening here? 这里发生了什么?

There are fractions of a second to each of your properties. 每个属性都有几分之一秒。 Most likely, your record wasn't created at an exact second, whereas any user-created time would be set as such. 最有可能的是,您的记录不是精确创建的,而任何用户创建的时间都是这样设置的。

Another possibility is the difference between datetime and datetime2 in SQL Server . 另一种可能性是SQL Server中datetimedatetime2之间差异

The DateTime type stores time at much higher precision than seconds. DateTime类型以比秒更高的精度存储时间。 They could be differing at millisecond or even tick (100 nanoseconds) level. 它们可以在毫秒或甚至滴答(100纳秒)水平上不同。

If you want to compare on a higher level, try this: 如果您想在更高级别进行比较,请尝试以下方法:

(p.ActionDate.Ticks / 10000000) > (fromDate.Ticks / 10000000)

Where 10000000 is the number of ticks in a second. 其中10000000是秒中的刻度数。 Since the / is an integer division that does truncate the fraction, you turn ticks into full seconds. 由于/是一个截断分数的整数除法,因此将刻度变为完整秒数。

UPDATE: 更新:

It seems like you are using entity framework. 看起来你正在使用实体框架。 The comparison above will possibly not work there. 上面的比较可能不适用于那里。 The solution is to run your original query against the database, do a ToList and then filter the results again in a LINQ2Objects query using the logic above. 解决方案是针对数据库运行原始查询,执行ToList ,然后使用上面的逻辑在LINQ2Objects查询中再次过滤结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM