Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enity Framework - Change default value

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?

like image 472
Jakob Busk Sørensen Avatar asked Nov 22 '25 00:11

Jakob Busk Sørensen


1 Answers

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

like image 145
DhruvJoshi Avatar answered Nov 24 '25 16:11

DhruvJoshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!