Enity Framework - Change default value

c# entity-framework entity-framework-6 sql-server

Question

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?

1
2
6/12/2018 12:32:50 PM

Popular Answer

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

1
11/18/2019 9:10:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow