C
C#4mo ago
Tarkacode

✅ 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 :
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Ingredient>().Property(i => i.CreatedOn).HasDefaultValue(DateTime.UtcNow);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Ingredient>().Property(i => i.CreatedOn).HasDefaultValue(DateTime.UtcNow);
}
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 :
modelBuilder.Entity<Ingredient>().Property(i => i.CreatedOn).HasDefaultValueSql("NOW()");
modelBuilder.Entity<Ingredient>().Property(i => i.CreatedOn).HasDefaultValueSql("NOW()");
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
public DateTime CreatedOn { get; set; } = DateTime.UtcNow;
public DateTime CreatedOn { get; set; } = DateTime.UtcNow;
Can it work? And also, is it a good practice? Or should I use the Entity model constructor, something like :
public class Ingredient
{
public Ingredient()
{
CreatedOn = DateTime.UtcNow;
}
}
public class Ingredient
{
public Ingredient()
{
CreatedOn = DateTime.UtcNow;
}
}
What do you think? I will very much appreciate every reply 🥳
6 Replies
Jimmacle
Jimmacle4mo ago
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/time
Tarkacode
Tarkacode4mo ago
Super cool, thanks a lot!
Jimmacle
Jimmacle4mo ago
now() at time zone 'utc' is what you want according to SO
Tarkacode
Tarkacode4mo ago
I 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
Jimmacle
Jimmacle4mo ago
i'm not sure there's much difference whether you do it client or DB side
Tarkacode
Tarkacode4mo ago
Ok, I see. Really cool. Thank you!!!