Entity Framework Code First:DateTime2 的哪个 DataType 属性?

Entity Framework Code First: which DataType attribute for DateTime2?

有时在使用 Entity Framework Code First 时,默认约定不会创建您想要的数据库类型。例如,默认情况下,类型 System.DateTime 的 属性 创建类型 DateTime 的数据库列。如果你想让它有datetime2类型(时区和夏令时都没有问题的DateTime类型)怎么办?

可以使用 DataTypeAtrribute 通过数据注释指定所需的数据库类型。 DataTypeAttribute accepts a parameter DataType Enumeration 的构造函数之一。所以可以指定如下内容:

[DataType(DataType.DateTime)]
public DateTime DateOfBirth {get; set;}

DataType 枚举类型包含很多类型,但是缺少 DateTime2 的值。

另一种方法是使用 Fluent API。在方法 DBContext.OnModelCreating:

中创建一个 DateTime2
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>().Property(p => p.BirthDate)
        .HasColumnType("datetime2");
}

DataTypeAttribute 有一个 second constructor that accepts a string。此字符串定义为

The name of the custom field template to associate with the data field.

所以人们会假设以下内容足以创建 datetime2:

[DataType("datetime2")]
public DateTime DateOfBirth {get; set;}

唉,这不行。创建的列仍然具有 DateTime 格式。

问题: 在构造函数中使用哪个字符串来创建 datetime2?

The DataType attribute is not used for column type mapping for Code First:

The Column annotation is a more adept in specifying the attributes of a mapped column. You can stipulate a name, data type or even the order in which a column appears in the table. [...] Don’t confuse Column’s TypeName attribute with the DataType DataAnnotation. DataType is an annotation used for the UI and is ignored by code first.

所以:

[Column(TypeName="datetime2")] 

对于那些仍然对如何定义属性的列类型感兴趣的人。从 EF 6.0 版开始,您可以定义某种类型的每个值都应具有某种数据库类型。

这是在 DbContext.OnModelCreating 中使用 DbModelBuilder.Properties 完成的。

如果这样做,您不必为每个 DateTime 编写属性或流利 API。保持一致并让所有 DateTime 具有相同的列类型更容易。同样,您可以为所有小数赋予相同的精度,即使将来添加小数也是如此。

假设您要定义每个 System.DateTime 都应具有列类型 DateTime2;每个 System.Decimal 都应该有一个具有指定精度的列类型。在 DbContext 中你会写:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // every property of type DateTime should have a column type of "datetime2":
    modelBuilder.Properties<DateTime>()
      .Configure(property => property.HasColumnType("datetime2"));
    // every property of type decimal should have a precision of 19
    // and a scale of 8:
    modelBuilder.Properties<decimal>()
        .Configure(property => property.HasPrecision(19, 8));
}