資料類型Data Types

注意

本節中的設定是一般適用於關聯式資料庫。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).

資料類型是指屬性所對應的資料行的資料庫特定型別。Data type refers to the database specific type of the column to which a property is mapped.

慣例Conventions

依照慣例,資料庫提供者,請選取屬性的 CLR 型別為基礎的資料類型。By convention, the database provider selects a data type based on the CLR type of the property. 它也會考量其他中繼資料,例如設定最大長度、 屬性是否為組件的主索引鍵等。It also takes into account other metadata, such as the configured Maximum Length, whether the property is part of a primary key, etc.

例如,SQL Server 會使用datetime2(7)DateTime屬性,和nvarchar(max)string屬性 (或nvarchar(450)string用做為索引鍵屬性)。For example, SQL Server uses datetime2(7) for DateTime properties, and nvarchar(max) for string properties (or nvarchar(450) for string properties that are used as a key).

資料註釋Data Annotations

您可以使用資料註解來指定確切的資料類型資料行。You can use Data Annotations to specify an exact data type for a column.

下列程式碼的設定,例如Url為最大長度的非 unicode 字串200Rating的有效位數為 decimal5及縮放的2For example the following code configures Url as a non-unicode string with maximum length of 200 and Rating as decimal with precision of 5 and scale of 2.

public class Blog
{
    public int BlogId { get; set; }
    [Column(TypeName = "varchar(200)")]
    public string Url { get; set; }
    [Column(TypeName = "decimal(5, 2)")]
    public decimal Rating { get; set; }
}

關於 fluent 應用程式開發介面Fluent API

您也可以使用 fluent 應用程式開發的應用程式開發介面來指定相同的資料類型的資料行。You can also use the Fluent API to specify the same data types for the columns.

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>(eb =>
        {
            eb.Property(b => b.Url).HasColumnType("varchar(200)");
            eb.Property(b => b.Rating).HasColumnType("decimal(5, 2)");
        });
    }
}

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