I have have a SQL Server table with default values on a lot of columns. An example is ModifiedDtm
(the time where the row was last modified), which will have GETDATE()
as default value. To avoid clashing with this, I have implemented it the following way in Entity Framework 6.2, using a code first approach:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime ModifiedDtm { get; set; }
This makes the default value works as intended when the row is created. However, it prevents me from ever updating the column again.
How do I make it so that SQL default values can be used, but still allow changing the value with EF later on?
You should consider using fluent API for this. In your context class add small bit for setting default value like below using HasDefaultValueSQL
class MyContext : DbContext
{
public DbSet<YourEntity> YourEntities{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<YourEntity>()
.Property(b => b.Created)
.HasDefaultValueSql("getdate()");
}
}
NOTE: This solution requires EF Core