实体属性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) 列,并将属性映射 stringnvarchar(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 字符串,其最大长度为 200Rating 小数位数为,小数 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 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 开始,可以使用 Fluent 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 属性,精度定义表示列将包含的任何值所需的最大位数,而 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 属性,精度定义表示秒的小数部分所需的最大位数,并且不使用小数位数。For DateTime properties, precision defines the maximum number of digits needed to express fractions of seconds, and scale is not used.

备注

在将数据传递给提供程序之前,实体框架不会进行任何精度验证或缩放。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 上创建类型为的列,并且 LastUpdated 将属性配置为具有精度3将导致类型为的列 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 的引用类型的新功能,该功能允许对引用类型进行批注,以指示它是否可用于包含空值。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 # 为空性配置属性: 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.

下面的示例显示了一个具有 required 和 optional 属性的实体类型, (默认) 并启用了 "可为 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.