简体   繁体   中英

How can I alter a model to set the SQL default date when using EF code migrations

Firstly, there are a lot of answers in this StackOverflow question that are of a similar ilk which helped me get very close, but none quite work in my situation.

I have a model class:

public class TestModel
{
    [Key]
    public int TestModelId { get; set; }
    public DateTime CreatedOn { get; set; }
}

And this is added to a DbContext file like so:

public virtual DbSet<TestModel> TestModels { get; set; }

So on add-migration this produces:

...
migrationBuilder.CreateTable(
    name: "TestModels",
    columns: table => new 
    {
        TestModelId = table.Column<int>(nullable:false)
            .Annotation("SqlServer:Identity", "1, 1"),
        CreatedOn = table.Column<DateTime>(nullable:false)
    },
    ...

Now I'm trying to get a one-stop place to make sure the CreatedOn column builder has the default GETDATE() in there:

CreatedOn = table.Column<DateTime>(nullable:false, defaultValueSql: "GETDATE()")

which I know works perfectly when translating it to the SQL Server side, but I've tried several data annotation and constructor versions as per the linked question to no avail eg the attribute

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

does nothing and I don't want to have to manually add the defaultValueSql part to the migration file every time I create one / it.

So where can I do this in the models?

You can accomplish that in the DbContext class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           modelBuilder.Property(x => x.CreatedOn).HasDefaultValueSql("getdate()");
           .....
        });

edit: needed to have the entity property of the modelBuilder in there too:

modelBuilder.Entity<TestModel>().Property...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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