0

設置日期DataAnnotations在數據庫優先EF 6還有就是要設置格式準則第一次遷徙的方法如何在MVC5

即:

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

不過,我可以在數據庫中首先實現相同的邏輯遷移,因爲每次更改都是數據庫正在更新模型。

所以,我的問題是:如何在數據庫第一次遷移中設置DataAnnotations像(DisplayFormat,DataFormatString等)。有可能嗎?如果可能的話,如何實施它。

回答

2

您可以利用生成的實體類是部分的並關聯元的事實數據雖然是另一類,並且MetadataTypeAttribute

例如,在不影響代碼生成一些代碼文件,你會寫是這樣的:

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

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

的「元數據」類並不需要包括實體的所有屬性 - 只是那些您想要將數據註釋與。

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

1

你可以改變視圖模型屬性與[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()) 
+0

Ravikumar,我沒有提到有關EF遷移。我想爲dataype設置格式。與日期格式類似,貨幣格式。我可以在Js中處理。但我正在尋找服務器端驗證。 – Aravin