✅ How to properly set a default value as UtcNow with EF Core and PostgreSQL
Hi there,
I use EF Core with a PostgreSQL DB. I want that each time I add an entity with EF Core in the DB, it saves the CreatedOn field with the value of the UtcNow.
I tried this :
But when I do "Add-Migration", I see that EF Core just saves the UtcNow once and will give this same value for every entity that I add.
If its 14h when I do the migration, every entity that I will add in the future will have this 14h value in the CreatedOn. It is not dynamic.
And the NOW() PostgreSQL function like this doesn't give the UtcNow unfortunately :
What are my options to do what I want to do?
I saw that I can write this property code in my EF Core Entity model
Can it work? And also, is it a good practice? Or should I use the Entity model constructor, something like :
What do you think?
I will very much appreciate every reply 🥳
6 Replies
the 2 examples at the bottom are effectively the same and are fine
if you want it generated on the DB side, you can use
HasDefaultValueSql
and provide whatever postgres function you want to use to get the current date/timeSuper cool, thanks a lot!
now() at time zone 'utc'
is what you want according to SOI tought about it! but I didn't find any postgres function that gives the UtcNow.
For example, the function now() gives you the datetime according to your server timezone unfortunately.
What do you think would be the benefits of having my datetime generated on the DB Side? If i find something that works?
Oh nice, I will try this too, thanksssss
i'm not sure there's much difference whether you do it client or DB side
Ok, I see. Really cool. Thank you!!!