LINQ DateTime Comparison Does Not Return Correct Results

I have the following LINQ to query the database and return the removed products from a specific date.

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 returns values ​​such as product.ActionDate.Value = {12/8/2016 11:41:00 AM} when fromDate was fromDate = {12/8/2016 11:41:00}}

The request clearly states: "MORE THAN". What's going on here?

+5
source share
2 answers

There are fractions of a second for each of your properties. Most likely, your record was not created with an accuracy of a second, while any time created by the user would be set as such.

Another possibility is the difference between datetime and datetime2 in SQL Server .

+3
source

The DateTime type stores time with much greater precision than seconds. They can differ at the level of a millisecond or even a tick (100 nanoseconds).

If you want to compare at a higher level, try the following:

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

Where 10000000 is the number of ticks per second. Since / is the whole division that truncates the fraction, you rotate ticks for full seconds.

UPDATE:

It seems you are using the framework entity. The comparison above may not work there. The solution is to run the original database query, make a ToList and then filter the results again in the LINQ2Objects query using the above logic.

0
source

Source: https://habr.com/ru/post/1260990/


All Articles