Override sql default value on insert using Entity Framework Core (7)

穿精又带淫゛_ 提交于 2019-12-11 06:14:46

问题


I have a table with a column [CreatedAtIsoUtc] that sets a Sql Server default value

migrationBuilder.CreateTable(
            name: "CurrentAccountLedger",
            columns: table => new
            {
                Id = table.Column<Guid>(nullable: false, defaultValueSql: "newsequentialid()"),
                CreatedAtIsoUtc = table.Column<DateTime>(nullable: false, defaultValueSql: "GETUTCDATE()"),                    
            }

        });

In a raw sql server query, I can insert a record and overwrite the [CreatedAtIsoUtc] default value.

In Entity Framework, I can't seem to overwrite this value when performing an Add() operation.

Any ideas on how I could get this working?


回答1:


Actually in EF Core v1.1.0 you can do that by setting the property to any value different than the default for the type (i.e. 0 for numbers, false for bool, null for string and nullable types, default(DateTime) in your case). The only current limitation is that you cannot override the sql default value with 0, false, null etc.

For instance

db.CurrentAccountLedger.Add(new CurrentAccountLedger { });

would insert a record with CreatedAtIsoUtc equals to the default GETUTCDATE(), while

db.CurrentAccountLedger.Add(new CurrentAccountLedger { CreatedAtIsoUtc = new DateTime(2017, 1, 1) });

would insert a record with the specified value.




回答2:


You can set raw SQL defaults on your entities in your context's OnModelCreating() using HasDefaultValueSql():

class YourContext : DbContext
{
    public DbSet<CurrentAccountLedger> CurrentAccountLedgers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CurrentAccountLedger>()
            .Property(x => x.CreatedAtIsoUtc)
            .HasDefaultValueSql("GETUTCDATE()");
    }
}


来源:https://stackoverflow.com/questions/41668301/override-sql-default-value-on-insert-using-entity-framework-core-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!