2013-07-05 111 views
0

我正在研究一個基於核心實體生成視圖模型的T4模板。 比如我有核心新聞類,我想這個模板來生成視圖模型,如這些在mvc4中讀取類屬性T4模板

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

假設你的「新聞」類所在,只要你想創建你的意見,你有兩種可能性同一項目內:

  1. 生成項目,然後引用輸出裝配在T4模板使用 <#@ assembly name="$(TargetPath)" #>。然後你可以在模板中使用標準反射來達到你想要的類。但要小心,你總是反映你的最後一個版本,可能已經過時和/或包含錯誤!
  2. 看看有形的T4編輯器。它是免費的,並提供語法突出顯示+針對T4模板的IntelliSense。它還有一個免費的模板庫,其中包含一個名爲「有形VisualStudio自動化助手」的模板。 包含這一個到您的模板,並使用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")) 
         { 
          ... 
         } 
        } 
    } 
    #> 
    

希望幫助!供參考;

+0

供參考;還有roslyn,它可以爲此使用text =>語法樹轉換。您也可以在T4中定義新聞的模型,並從中避免使用外部工具或反射來生成所有變體。 – FuleSnabel