一个重要的数据库特性是具有计算属性的能力。如果您将代码优先类映射到包含计算属性的表,您不希望 Entity Framework 尝试更新这些列。但您确实希望 EF 在插入或更新数据后从数据库中返回这些值。您可以使用 DatabaseGenerated 注释来标记类中的这些属性以及 Computed 枚举。其他枚举是 None 和 Identity。
[DatabaseGenerated(DatabaseGenerationOption.Computed)]
public DateTime DateCreated { get; set; }
现在只需让您的数据库在创建记录时生成时间戳。您也可以像这样将 DataAnnotation 设置为只读
[DatabaseGenerated(DatabaseGenerationOption.Computed)]
[Editable(false)]
public DateTime DateCreated { get; set; }
希望这会有所帮助
更新
// Private
private DateTime _createdOn = DateTime.Now;
// Public property
[Display(Name = "Created On")]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreatedOn
{
get
{
return (_createdOn == DateTime.MinValue) ? DateTime.Now : _createdOn;
}
set { _createdOn = value; }
}
或者在视图中。
@Html.HiddenFor(model => model.CommentTime, new { @Value=System.DateTime.Now })
或者在控制器中。
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
如果在控制器和/或模型中完成,您可以像这样使用 readonly 的 html 属性。
您可以使用自定义编辑器模板:
public class MyViewModel
{
[UIHint("MyHiddenDate")]
public DateTime Date { get; set; }
}
然后定义~/Views/Shared/EditorTemplates/MyHiddenDate.cshtml:
@model DateTime
@Html.Hidden("", Model.ToString("dd/MM/yyyy"))
最后在你看来使用 EditorFor 助手:
@model MyViewModel
@Html.EditorFor(x => x.Date)
这将为视图模型的 Date 属性呈现自定义编辑器模板,并因此使用所需格式呈现具有值的隐藏字段。
更新
EditorFor html 帮助器没有采用 HTML 属性的重载。在这种情况下,您需要使用更具体的内容,例如 TextBoxFor:
<div class="editor-field">
@Html.TextBoxFor(model => model.DateCreated , new
{ disabled = "disabled", @readonly = "readonly" })
</div>
您仍然可以使用 EditorFor,但您需要在自定义 EditorTemplate 中有一个 TextBoxFor:
public class MyModel
{
[UIHint("DateCreated ")]
public string DateCreated { ;get; set; }
}
然后,在您的 Views/Shared/EditorTemplates 文件夹中,创建一个文件 DateCreated .cshtml。在该文件中,输入以下内容:
@model string
@Html.TextBoxFor(m => m, new { @readonly = "readonly" })