預設值Default Values

注意

本節中的組態一般適用於關聯式資料庫。The configuration in this section is applicable to relational databases in general. 當您因共用 Microsoft.EntityFrameworkCore.Relational 套件而安裝關聯式資料庫提供者時,這裡顯示的擴充方法會變成可用。The extension methods shown here will become available when you install a relational database provider (due to the shared Microsoft.EntityFrameworkCore.Relational package).

資料行的預設值是將會插入,如果在插入新的資料列,但未指定值的資料行的值。The default value of a column is the value that will be inserted if a new row is inserted but no value is specified for the column.

慣例Conventions

依照慣例,未設定預設值。By convention, a default value is not configured.

資料註釋Data Annotations

您可以設定使用資料註解的預設值。You can not set a default value using Data Annotations.

Fluent APIFluent API

您可以使用 Fluent API,來指定屬性的預設值。You can use the Fluent API to specify the default value for a property.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Rating)
            .HasDefaultValue(3);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public int Rating { get; set; }
}

您也可以指定用來計算的預設值的 SQL 片段。You can also specify a SQL fragment that is used to calculate the default value.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Created)
            .HasDefaultValueSql("getdate()");
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public DateTime Created { get; set; }
}