t4 模板总结

模板包含如下几种block

  1. 指令<#@ DirectiveName [AttributeName = “AttributeValue”] … #> 
  2. 代码块 <# code #> (Expression block ( <#= exp #>))
  3. features block <#+ code #>:用添加新的方法、属性、类等
  4. 文本块

Text blocks are converted to calls to the Write method from the TextTransformation class.
Expression blocks are converted to calls to the ToStringWithCulture method of the ToStringHelper class.
Code blocks are evaluated directly in whatever method they are defined in. If a feature block has not been defined, they are evaluated in the override of the TransformText method.

模板基类Microsoft.VisualStudio.TextTemplating.TextTransformation,包含属性Host(IServiceProvider,ITextTemplatingEngineHost )(需template指令hostspecific=true),Session(Dictionary<string,object>)。

parameter指令中的参数从Session or CallingContext获取,CallingContext用于表示模板自身(可取于获取模板this的属性)。

Text Template与Run Time Template

The first big difference is the custom tool used. For text templates, the Custom Tool is TextTemplatingFileGenerator. For run time templates, the Custom Tool is TextTemplatingFilePreProcessor.
The second big difference is the output from the template. With text templates, the output is the result of running the template. Behind the scenes, we saw that T4 creates an intermediary class and then compiles this class. The output we get comes from instantiating this class and calling the TransformText method. For text templates, T4 does all of this for us as a single step, and we can see the output in the nested related file.
For run time templates, our job is a bit more involved, while T4 gets off a bit easier. The output of running the Custom Tool on a run time template is the intermediary class. We are expected to instantiate this class at runtime and explicitly call the TransformText method directly to get the results. This gives us a great deal more control over calling the template.

常用程序集

  1. EnvDte(EnvDte.DTE类在此),EnvDTE100,EnvDTE80
  2. Microsoft.SqlServer.Smo(Server,Database,Table,Column等在此)
    Microsoft.SqlServer.ConnectionInfo
    Microsoft.SqlServer.Management.Sdk.Sfc
  3. Microsoft.Data.Entity.Design(Microsoft.Data.Entity.Design.CodeGeneration.EdmHelper类在此)

几个代码片段

var path = this.Host.ResolvePath (@"..\WebApi\bin\WebApi.dll");
public string FindConfigFile () { 
    var visualStudio = (this.Host as IServiceProvider).GetService(typeof(EnvDTE.DTE))  as EnvDTE.DTE;  
    var project =   visualStudio.Solution.FindProjectItem  (this.Host.TemplateFile).ContainingProject as EnvDTE.Project;  
    foreach (EnvDTE.ProjectItem item in project.ProjectItems)  {    
        if (item.FileNames[0].EndsWith(".config"))     {    
            return item.FileNames[0];     
        }   
    }   
    return ""; 
}
var server=new Server("conn");	//创建连接对象
var dbs=server.Databases;	//所有数据库
var db=new Database(server,"mydb");	//选择数据库对象
db.Refresh();
var tbs=db.Tables;	//所有表
var tb=tbs[0];
var columns=tb.Columns;	//所有列

 

发表评论

电子邮件地址不会被公开。