The Fluent API HasDefaultValueSql Method

The Entity Framework Core Fluent API HasDefaultValueSql method is used to specify the expression used to generate the default value for a database column mapped to a property.

public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public bool IsActive { get; set; }
    public DateTime DateCreated { get; set; }
}

public clas SampleContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Context>()
            .Propery(p => p.DateCreated)
            .HasDefaultValueSql("GetUtcDate()");
    }
}

Data Annotations

It is not possible to configure default database column values using data annotations.


Created:
Last updated: 14/03/2017 16:33:44
Proficiency Level: Beginner