2

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I originally tried this but it wasn't working for some reason. Just re-ran and it works. Not sure where I messed up.
Does it means that with EfCore null value can NOT be inserted to nullable column which has default value: stackoverflow.com/questions/41969303/…
@Boris Indeed (null for string and nullable types)
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()");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.