Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime.UtcNow in Entity Framework query evaluated different than DateTime.UtcNow in C# IL

Are DateTime functions in an EF query evaluated by the SQL Server, as where DateTime functions outside of the query expression are evaluated by the machine running the IL?

I have an application that has SalesOrders

public class SalesOrder
{
   public Int32 OrderID {get;set;}
   public DateTime Expiration {get;set;} 
}

I run an EF query and get different results when I do this:

DateTime utcnow = DateTime.UtcNow;

var open = (from a in context.SalesOrders
            where a.Expiration > utcnow
            select a).ToList();

Than when I do this:

var open = (from a in context.SalesOrders
            where a.Expiration > DateTime.UtcNow
            select a).ToList();

I think this is because DateTime.UtcNow in an Entity Framework query is evaluated by the SQL Server, vs DateTime.UtcNow outside of the query is evaluated by the machine that's running the IL; I'm basing that off this answer.

I'm in Azure platform as a service, debugging locally with an Azure SQL DB, if that matters.

like image 778
Eric Avatar asked Jan 08 '16 19:01

Eric


People also ask

What is difference between DateTime UtcNow and DateTime now?

UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime. Now gives the date and time as it would appear to someone in your current locale.

What is UtcNow ()?

UTCNOW() Current date and time in UTC. Returns the current date and time ( DateTime value) in Coordinated Universal Time (UTC).

What does DateTime now give?

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).


2 Answers

Your thoughts are correct.

On SQL Server, your first query runs the following SQL query:

exec sp_executesql N'SELECT 
    [Extent1].[OrderID] AS [OrderID], 
    [Extent1].[Expiration] AS [Expiration]
    FROM [dbo].[SalesOrders] AS [Extent1]
    WHERE [Extent1].[Expiration] > @p__linq__0',N'@p__linq__0 datetime2(7)',@p__linq__0='2016-01-08 20:05:25.4433282'

It is clear here that the client's time is passed in as a parameter.

Your second query sends this to SQL server:

SELECT 
    [Extent1].[OrderID] AS [OrderID], 
    [Extent1].[Expiration] AS [Expiration]
    FROM [dbo].[SalesOrders] AS [Extent1]
    WHERE [Extent1].[Expiration] > (SysUtcDateTime())

Here it is clear that the SQL Server clock is used.

like image 60
Yacoub Massad Avatar answered Nov 01 '22 08:11

Yacoub Massad


DateTime.UtcNow is mapped to CurrentUtcDateTime(). Here is a full list:

CLR Method to Canonical Function Mapping

like image 2
Giorgi Avatar answered Nov 01 '22 08:11

Giorgi