3

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
  • 1
    Possible duplicate of [Entity Framework 6 Code first Default value](https://stackoverflow.com/questions/19554050/entity-framework-6-code-first-default-value) – CodeNotFound Jun 12 '18 at 12:42

1 Answers1

1

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

FoggyDay
  • 11,962
  • 4
  • 34
  • 48
DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60