读取mvc4 T4模板中的类属性

时间:2013-07-05 19:46:22

标签: c# asp.net-mvc asp.net-mvc-4 t4 scaffolding

我正在开发一个T4模板,它将根据核心上的实体生成View Models。 例如,我在Core中有News类,我希望这个模板生成像这样的视图模型

public class News
{
    public property int Id {get;set;}
    public property string Title {get;set;}
    public property string Content {get;set;}
}

public class NewsCreate
{
    public property int Id {get;set;}
    public property string Title {get;set;}
    public property string Content {get;set;}
}
public class NewsUpdate
{
    public property int Id {get;set;}
    public property string Title {get;set;}
    public property string Content {get;set;}
} 

现在只是这两个。但我找不到获取News类属性的方法。 我怎样才能用反射来得到它们。 。 。

1 个答案:

答案 0 :(得分:1)

假设您的“新闻”类位于同一个项目中,您希望在其中创建视图,您有两种可能:

  1. 构建项目,然后使用T4模板引用输出程序集 <#@ assembly name="$(TargetPath)" #>。然后,您可以在模板中使用标准反射来达到所需的类。但要小心,你总是反映你可能已经过时和/或包含错误的最后一个版本!
  2. 看看有形的T4编辑器。它是免费的,为T4模板提供语法高亮+ IntelliSense。它还有一个免费的模板库,其中包含一个名为“有形的VisualStudio Automation Helper”的模板。 将此文件包含在模板中,并使用Visual Studio代码模型迭代当前解决方案中的所有类:

    <# var project = VisualStudioHelper.CurrentProject;
    
    // get all class items from the code model
    var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);
    
    // iterate all classes
    foreach(EnvDTE.CodeClass codeClass in allClasses)
    {
        // iterate all properties
        var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementProperty, true);
        foreach(EnvDTE.CodeProperty property in allProperties)
        {
            // check if it is decorated with an "Input"-Attribute
            if (property.Attributes.OfType<EnvDTE.CodeAttribute>().Any(a => a.FullName == "Input"))
            {
                ...
            }
        }
    }
    #>
    
  3. 希望有所帮助!

相关问题