在 t4 模板中检测 Class 继承

Detect Class Inheritance in t4 template

你能检测到 t4 模板中的 class' 继承属性吗?

我有两个 class 是这样的:

public class User : ManagedRecord
{
   public int UserId { get; set;}
   public string UserName { get; set;}
}

public abstract class ManagedRecord
{
   public int Deleted { get; set;}
   public DateTime CreatedDate { get; set;}
}

当 t4 模板创建基于用户的字段时,它将首先放置 ManagedRecord 字段,然后是用户的字段。

有没有办法检测继承的 class 字段,以便我可以不同地处理它们?

t4 模板用于 ASP.NET MVC 5 编辑页面模板,它根据使用的 class 创建表单字段。

t4 代码如下所示:

<#@ template language="C#" HostSpecific="True" #>
<#@ output extension=".cshtml" #>
<#@ include file="Imports.include.t4" #>
@model <#= ViewDataTypeName #>
<#
    string boolType = "System.Boolean";
    int tabIndex = 1;
    bool autofocus = true;
    Version requiredMvcVersion = new Version("5.1.0.0");
    bool isControlHtmlAttributesSupported = MvcVersion >= requiredMvcVersion;


foreach (PropertyMetadata property in ModelMetadata.Properties) {
if (property.Scaffold && !property.IsAssociation) {
#>
    @Html.EditorFor(model => model.<#= property.PropertyName #>)
<#
}
#>

我找到了适合我的场景的解决方案。您可以修饰属性以表明您不想搭建列的脚手架。

using System.ComponentModel.DataAnnotations;
namespace YourNameSpace
{
    public abstract class ManagedRecord
    {
        [ScaffoldColumn(false)]
        public DateTime CreatedDate{ get; set; }

        [ScaffoldColumn(false)]
        public bool Deleted { get; set; }
    }
}