Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework, getutcdate()

Can I use the SQL-function getutcdate() from entity framework to set a date field in the database when saving an entity object?

like image 539
Freddy Avatar asked Oct 31 '25 02:10

Freddy


2 Answers

Yes, you can do this. The CLR function DateTime.UtcNow is mapped to the canonical function CurrentUtcDateTime, which should translate, for SQL Server to GETUTCDATE() or similar.

var q = from e in Context.MyEntities
        select new
        {
            Entity = e,
            Time = DateTime.UtcNow
        };
like image 106
Craig Stuntz Avatar answered Nov 01 '25 17:11

Craig Stuntz


when saving an entity object

I think what is asked here is: can I make EF insert/update a database row and set GETUTCDATE() in the SQL statement.

That's not the same as first getting a DateTime value from the database, setting the result in an object's property and then saving the object. That always stores a value that's "ages" before the actual current value at save time. Therefore, all the answers telling how to get GETUTCDATE() don't really answer the question.

In EF, to this day, it's impossible to generate insert statements containing GETUTCDATE(). In update statements it's only possible by bulk updates introduced in EF-core 7

A statement like...

Products.ExecuteUpdate(p => p.SetProperty(x => x.IntroductionDate, DateTime.UtcNow));

...produces a SQL statement like this:

UPDATE [p]
SET [p].[IntroductionDate] = GETUTCDATE()
FROM [Products] AS [p]

I.e. it doesn't interpolate the C# DateTime.UtcNow value but translates it into SQL.

like image 42
Gert Arnold Avatar answered Nov 01 '25 18:11

Gert Arnold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!