.net MVC 脚手架模板:检查模型是否包含 属性

.net MVC scaffold template: Check if model contains property

我正在尝试修改搭建控制器的模板,以检查模型是否包含某些 属性,如果包含,请编写 C# 代码为其赋值。所以在我的模板中,在编写 Create actionresult (post) 的部分:

        [HttpPost]
        [ValidateAntiForgeryToken]
<# if (UseAsync) { #>
        public async Task<ActionResult> Create(<#= bindAttribute #><#= ModelTypeName #> <#= ModelVariable #>)
<# } else { #>
        public ActionResult Create(<#= bindAttribute #><#= ModelTypeName #> <#= ModelVariable #>)
<# } #>
        {



    <#
    if (THE MODEL CONTAINS A PROPERTY NAMED "creation_date")) { 
    #>
        <#= modelVariable #>.creation_date = DateTime.Now;
    <# } #>

有办法吗?

好的,我自己找到了答案,不确定它是最好的解决方案,但它工作得很好:

<#
bool entityWithCreationDate = false;
foreach (PropertyMetadata property in ModelMetadata.Properties) {
    if(property.PropertyName == "creation_date") { entityWithCreationDate=true; break; }
}
if(entityWithCreationDate==true) {
#>
        <#= ModelVariable #>.creation_date = DateTime.Now;      
<#
}
#>