简体   繁体   English

实体框架 - 更改默认值

[英]Enity Framework - Change default value

I have have a SQL Server table with default values on a lot of columns.我有一个 SQL Server 表,在很多列上都有默认值。 An example is ModifiedDtm (the time where the row was last modified), which will have GETDATE() as default value.一个例子是ModifiedDtm (上次修改行的时间),它将GETDATE()作为默认值。 To avoid clashing with this, I have implemented it the following way in Entity Framework 6.2, using a code first approach:为了避免与此冲突,我在 Entity Framework 6.2 中使用代码优先方法以以下方式实现了它:

[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?如何使它可以使用 SQL 默认值,但仍允许稍后使用 EF 更改该值?

You should consider using fluent API for this.您应该考虑为此使用 fluent API。 In your context class add small bit for setting default value like below using HasDefaultValueSQL在您的上下文类中,使用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注意:此解决方案需要 EF Core

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM