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

entity-framework entity-framework-core

Question

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
1
1/16/2017 1:33:59 AM

Accepted Answer

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.

3
1/16/2017 7:08:52 PM

Popular Answer

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()");
    }
}


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