I'm having a strange issue when configuring my entities in Fluent API using EF Core.
All my entities have an EntityCreated
field which is a DateTime object that is set to the current DateTime upon being added to the database as a new record.
The following is my configuration code to set this default value:
builder.Property(x => x.EntityCreated).HasDefaultValue(DateTime.Now);
The problem is that every time a new record is added, instead of using the current DateTime, it will use the first DateTime used when it created the first record in the db.
I'm very confused as I've checked that this DateTime is not being set anywhere else before being commited to the db, I'm unsure if anyone else has had the same issue but I'm sort of scratching my head over this since I've also tried a few other methods such as:
1) builder.Property(x => x.EntityCreated).HasDefaultValueSql("getdate()");
2) builder.Property(x => x.EntityCreated).HasComputedColumnSql("getdate()");
Can anyone assist on this issue?
Much appreciated.
Ok I figured out the issue.
Because of the configuration:
builder.Property(x => x.EntityCreated).HasDefaultValue(DateTime.Now);
When I created a migration, it was using the DateTime that was generated at the time of creating said migration. As a result, it made the default value for this field a static DateTime.
To overcome this, I reverted the migration back to previous, and used the following configuration:
builder.Property(x => x.EntityCreated).HasDefaultValueSql("getdate()");
I then created a new migration and updated the db.
This has now solved my problem.