简体   繁体   中英

LINQ to EF4 datetime comparison problems

I have a problem while comparing smalldatetime/datetime column value from DB(SQL Server 2008) with DateTime.Now in C#. I know that datetime format in DB and on the server on which application is running are different, so I have done something like this to "cache" the results so date time comparison will be local and not be on server:

var inactiveAccounts = (from entry in ent.Accounts
                           where entry.Status == 0                                           
                           select entry).ToArray();

var accountsFiltered = (from entry in inactiveAccounts
                     where entry.DeactivationDate < DateTime.Now
                     select entry).ToArray(); 

And at some pertiod of day I am not getting the right records.

I suspect it is due to where entry.DeactivationDate < DateTime.Now date comparison. And seems in EF it is tricky to work with datetime, please help me to identify the problem.

Don´t know if it solves your problem but i would create a local variable and set DateTime.Now on it. Then use the local variable in your linq query.

This is done, because DateTime.Now gets evaluated in your query each time the where clause is called. So for each entry in inactiveAccounts you are working against another DateTime.

Also if you want to compare Dates without the Time value, you should use DateTime.Today

var inactiveAccounts = (from entry in ent.Accounts
                       where entry.Status == 0                                           
                       select entry).ToArray();

DateTime currentDateTime = DateTime.Now;

var accountsFiltered = (from entry in inactiveAccounts
                 where entry.DeactivationDate < currentDateTime 
                 select entry).ToArray(); 

You can use this directly:

var inactiveAccounts = (from entry in ent.Accounts
                        where entry.Status == 0 && entry.DeactivationDate < DateTime.Now                  
                        select entry).ToArray();

Because DataTime.Now and DateTime.UtcNow are translated as canonical functions = they should not be evaluated on .NET side but translated to GETDATE() or GETUTCDATE() SQL function calls respectively.

The rest of your question is unanswerable because providing information like

And at some period of day I am not getting the right records.

You must put much bigger effort to analysis of the problem if you want to get answer including which periods cause problem, what timezones are used, etc. Generally we will not help you with that because we don't see your data. It is also not a problem of EF because in your case it happends completely in linq-to-object = plain .NET code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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