實體屬性Entity Properties

模型中的每個實體類型都有一組屬性,EF Core 會從資料庫讀取和寫入。Each entity type in your model has a set of properties, which EF Core will read and write from the database. 如果您是使用關係資料庫,實體屬性會對應到資料表資料行。If you're using a relational database, entity properties map to table columns.

包含和排除的屬性Included and excluded properties

依照慣例,所有具有 getter 和 setter 的公用屬性都會包含在模型中。By convention, all public properties with a getter and a setter will be included in the model.

可以排除特定的屬性,如下所示:Specific properties can be excluded as follows:

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

    [NotMapped]
    public DateTime LoadedFromDatabase { get; set; }
}

資料行名稱Column names

依照慣例,當使用關係資料庫時,實體屬性會對應到名稱與屬性相同的資料表資料行。By convention, when using a relational database, entity properties are mapped to table columns having the same name as the property.

如果您想要使用不同的名稱來設定資料行,可以這麼做,如下列程式碼片段所示:If you prefer to configure your columns with different names, you can do so as following code snippet:

public class Blog
{
    [Column("blog_id")]
    public int BlogId { get; set; }
    public string Url { get; set; }
}

資料行資料類型Column data types

使用關係資料庫時,資料庫提供者會根據屬性的 .NET 類型選取資料類型。When using a relational database, the database provider selects a data type based on the .NET 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 會將屬性對應至資料行,並將屬性對應至資料 DateTime datetime2(7) string nvarchar(max) 行 (或用於 nvarchar(450) 作為索引鍵) 的屬性。For example, SQL Server maps DateTime properties to datetime2(7) columns, and string properties to nvarchar(max) columns (or to nvarchar(450) for properties that are used as a key).

您也可以設定資料行來指定資料行的精確資料類型。You can also configure your columns to specify an exact data type for a column. 例如,下列程式碼會將 Url 最大長度為的非 unicode 字串設定為,並將精確度設定為 200 Rating decimal 5 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; }
}

長度上限Maximum length

設定 [最大長度] 會為資料庫提供者提供適當的資料行資料類型的提示,以選擇指定的屬性。Configuring a maximum length provides a hint to the database provider about the appropriate column data type to choose for a given property. 最大長度只適用于陣列資料類型,例如 stringbyte[]Maximum length only applies to array data types, such as string and byte[].

注意

Entity Framework 在將資料傳遞給提供者之前,不會執行任何最大長度驗證。Entity Framework does not do any validation of maximum length before passing data to the provider. 由提供者或資料存放區進行驗證(如果適合的話)。It is up to the provider or data store to validate if appropriate. 例如,以 SQL Server 為目標時,超過最大長度將會導致例外狀況,因為基礎資料行的資料類型不允許儲存多餘的資料。For example, when targeting SQL Server, exceeding the maximum length will result in an exception as the data type of the underlying column will not allow excess data to be stored.

在下列範例中,設定最大長度500會導致 nvarchar(500) 在 SQL Server 上建立類型的資料行:In the following example, configuring a maximum length of 500 will cause a column of type nvarchar(500) to be created on SQL Server:

public class Blog
{
    public int BlogId { get; set; }
    [MaxLength(500)]
    public string Url { get; set; }
}

精確度和小數位數Precision and Scale

從 EFCore 5.0 開始,您可以使用流暢的 API 來設定精確度和小數位數。Starting with EFCore 5.0, you can use fluent API to configure the precision and scale. 它會告訴資料庫提供者所需的資料行需要多少儲存體。It tells the database provider how much storage is needed for a given column. 它只適用于資料類型,而提供者允許精確度和小數位數的變化-通常是 decimalDateTimeIt only applies to data types where the provider allows the precision and scale to vary - usually decimal and DateTime.

decimal若為屬性,precision 會定義表示資料行將包含的任何值所需的最大位數,且 scale 會定義所需的最大小數位數。For decimal properties, precision defines the maximum number of digits needed to express any value the column will contain, and scale defines the maximum number of decimal places needed. DateTime若為屬性,precision 會定義用來表示秒數的最大位數,且不使用小數位數。For DateTime properties, precision defines the maximum number of digits needed to express fractions of seconds, and scale is not used.

注意

Entity Framework 在將資料傳遞給提供者之前,不會執行任何精確度或規模的驗證。Entity Framework does not do any validation of precision or scale before passing data to the provider. 由提供者或資料存放區視需要進行驗證。It is up to the provider or data store to validate as appropriate. 例如,以 SQL Server 為目標時,資料類型的資料行 datetime 不允許設定有效位數,而一個資料行的有效 datetime2 位數可以是介於0和7(含)之間。For example, when targeting SQL Server, a column of data type datetime does not allow the precision to be set, whereas a datetime2 one can have precision between 0 and 7 inclusive.

在下列範例中, Score 將屬性設定為具有有效位數14和小數位數2會導致 decimal(14,2) 在 SQL Server 上建立類型的資料行,並將屬性設定為具有有效位數3的資料 LastUpdated 行,將會導致類型的資料行 datetime2(3)In the following example, configuring the Score property to have precision 14 and scale 2 will cause a column of type decimal(14,2) to be created on SQL Server, and configuring the LastUpdated property to have precision 3 will cause a column of type datetime2(3):

目前無法使用資料批註進行設定。Currently not possible to use data annotations to configure.

必要和選用屬性Required and optional properties

如果屬性可包含,則會將其視為選擇性 nullA property is considered optional if it is valid for it to contain null. 如果不是 null 要指派給屬性的有效值,則會將它視為必要屬性。If null is not a valid value to be assigned to a property then it is considered to be a required property. 對應到關係資料庫架構時,需要的屬性會建立為不可為 null 的資料行,而選擇性的屬性會建立為可為 null 的資料行。When mapping to a relational database schema, required properties are created as non-nullable columns, and optional properties are created as nullable columns.

慣例Conventions

依照慣例,其 .NET 型別可以包含 null 的屬性會設定為選擇性,而 .NET 型別不能包含 null 的屬性則會設定為必要。By convention, a property whose .NET type can contain null will be configured as optional, whereas properties whose .NET type cannot contain null will be configured as required. 例如,所有具有 .net 實值型別 (intdecimal 、等 bool ) 的屬性都會設定為必要,且所有具有可為 null 之 .net 實值型別的屬性 (int?decimal? ) 、等等) bool? 都會設定為選擇性。For example, all properties with .NET value types (int, decimal, bool, etc.) are configured as required, and all properties with nullable .NET value types (int?, decimal?, bool?, etc.) are configured as optional.

C # 8 引進了新的功能,稱為 可為 null 的參考型別,可讓您標注參考型別,以指出其是否有效,以包含 null。C# 8 introduced a new feature called nullable reference types, which allows reference types to be annotated, indicating whether it is valid for them to contain null or not. 預設會停用此功能,如果已啟用,則會以下列方式修改 EF Core 的行為:This feature is disabled by default, and if enabled, it modifies EF Core's behavior in the following way:

  • 如果 (預設) 停用可為 null 的參考型別,則所有具有 .NET 參考型別的屬性都會依照慣例設定為選擇性 (例如 string) 。If nullable reference types are disabled (the default), all properties with .NET reference types are configured as optional by convention (for example, string).
  • 如果已啟用可為 null 的參考型別,則會根據其 .NET 類型的 c # null 屬性來設定屬性: string? 將設定為選擇性,但 string 會設定為必要。If nullable reference types are enabled, properties will be configured based on the C# nullability of their .NET type: string? will be configured as optional, but string will be configured as required.

下列範例顯示具有必要和選擇性屬性的實體類型,並停用 (預設) 和啟用的可為 null 參考功能:The following example shows an entity type with required and optional properties, with the nullable reference feature disabled (the default) and enabled:

public class CustomerWithoutNullableReferenceTypes
{
    public int Id { get; set; }
    [Required]                               // Data annotations needed to configure as required
    public string FirstName { get; set; }    
    [Required]
    public string LastName { get; set; }     // Data annotations needed to configure as required
    public string MiddleName { get; set; }   // Optional by convention
}

建議使用可為 null 的參考型別,因為它會將以 c # 程式碼表示的 null 屬性傳送給 EF Core 的模型和資料庫,並毋使用流暢的 API 或資料注釋,以表達相同的概念兩次。Using nullable reference types is recommended since it flows the nullability expressed in C# code to EF Core's model and to the database, and obviates the use of the Fluent API or Data Annotations to express the same concept twice.

注意

在現有的專案上啟用可為 null 的參考型別時,請務必注意:先前設定為選用的參考型別屬性現在會設定為必要,除非它們明確標注為可為 null。Exercise caution when enabling nullable reference types on an existing project: reference type properties which were previously configured as optional will now be configured as required, unless they are explicitly annotated to be nullable. 管理關係資料庫架構時,這可能會導致產生遷移,進而改變資料庫資料行的 null 屬性。When managing a relational database schema, this may cause migrations to be generated which alter the database column's nullability.

如需可為 null 的參考型別,以及如何搭配 EF Core 使用這些類型的詳細資訊, 請參閱這項功能的專用檔頁面For more information on nullable reference types and how to use them with EF Core, see the dedicated documentation page for this feature.

明確設定Explicit configuration

慣例可以設定為選擇性的屬性,如下所示:A property that would be optional by convention can be configured to be required as follows:

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

資料行定序Column collations

注意

這項功能是在 EF Core 5.0 中引進。This feature is introduced in EF Core 5.0.

您可以在文字資料行上定義定序,以決定如何比較和排序定序。A collation can be defined on text columns, determining how they are compared and ordered. 例如,下列程式碼片段會將 SQL Server 資料行設定為不區分大小寫:For example, the following code snippet configures a SQL Server column to be case-insensitive:

modelBuilder.Entity<Customer>().Property(c => c.Name)
    .UseCollation("SQL_Latin1_General_CP1_CI_AS");

如果資料庫中的所有資料行都需要使用特定定序,請改為在資料庫層級定義定序。If all columns in a database need to use a certain collation, define the collation at the database level instead.

您可以在 定 [序檔] 頁面中找到有關定序 EF Core 支援的一般資訊。General information about EF Core support for collations can be found in the collation documentation page.