如何在 MVC5 上的 Database First EF 6 中为日期设置 DataAnnotations

How to set DataAnnotations for Date in Database First EF 6 on MVC5

代码优先迁移中有一种设置格式的方法

即:

..
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]
public Nullable<System.DateTime> DeliveredDate { get; set; }
..

但是,我可以在数据库首次迁移中实现相同的逻辑,因为每次更改都是数据库在更新模型。

所以,我的问题是:如何在数据库首次迁移中设置 DataAnnotations,如(DisplayFormat、DataFormatString 等)?有可能吗?如果可以,如何实现。

您可以使用 [DisplayFormat] 属性更改视图模型 属性:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
               ApplyFormatInEditMode = true)]
public DateTime DeliveredDate { get; set; }

在您看来:

@Html.EditorFor(x => x.DeliveredDate )
or, for displaying the value,

@Html.DisplayFor(x => x.DeliveredDate )

或者您可以这样做:

@Html.TextBox("MyDate", Model.DeliveredDate .ToLongDateString())

您可以利用生成的实体 class 是部分实体这一事实,并通过另一个 class 和 MetadataTypeAttribute.

关联元数据

例如,在一些不受代码生成影响的代码文件中,你会这样写:

[MetadataType(typeof(YourEntityMetadata))]
partial class YourEntity { }

class YourEntityMetadata
{
    [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]
    public Nullable<System.DateTime> DeliveredDate { get; set; }
}

"metadata" class 不需要包含实体的所有属性 - 只需包含您要与数据注释相关联的属性。

参考:EF Database First with ASP.NET MVC: Enhancing Data Validation