C# 读取mvc4 T4模板中的类属性
我正在开发一个T4模板,该模板将基于core上的实体生成视图模型。 例如,我在Core中有一个News类,我希望这个模板能够生成如下视图模型C# 读取mvc4 T4模板中的类属性,c#,asp.net-mvc,asp.net-mvc-4,t4,scaffolding,C#,Asp.net Mvc,Asp.net Mvc 4,T4,Scaffolding,我正在开发一个T4模板,该模板将基于core上的实体生成视图模型。 例如,我在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 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类的属性。
我如何使用反射来获取它们和 假设您的“News”类位于您希望在中创建视图的同一项目中,您有两种可能性:
。然后,您可以在模板内使用标准反射来达到所需的类。但是要小心,您总是反映您的上一个版本可能已经过时和/或包含错误李>
<# 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"))
{
...
}
}
}
#>
a.FullName==“输入”))
{
...
}
}
}
#>
希望有帮助 供参考;还有roslyn,它进行text=>语法树转换,可以用于此。您还可以在T4中定义新闻模型,并从中生成所有变体,以避免外部工具或反射。