Template文件
代码语言:javascript复制<#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<#@ assembly name="Microsoft.SqlServer.Smo" #>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>
<#@ import namespace="System" #>
<#@ import namespace="Microsoft.SqlServer.Management.Smo" #>
<#
public class ProcedureTemplate : Template
{
public string DatabaseName {get; private set;}
public string TableName{get;private set;}
public Table Table {get; private set;}
public const string VersionNoField = "VERSION_NO";
public const string VersionNoParameterName = "@p_version_no";
public ProcedureTemplate(string databaseName, string tableName)
{
this.DatabaseName = databaseName;
this.TableName = tableName;
}
public virtual string GetProcedureName()
{
return this.TableName "M";
}
public override string TransformText()
{
Server server = new Server();
Database database = new Database(server, DatabaseName);
var table = new Table(database, TableName);
table.Refresh();
WriteLine("using System;");
WriteLine("using System.Runtime.Serialization;");
WriteLine("namespace RTMDemo.Model");
WriteLine("{");
PushIndent("t");
WriteLine("[DataContract]");
WriteLine("public class {0}M",TableName);
WriteLine("{");
PushIndent("t");
for(int i=0; i<table.Columns.Count;i )
{
Column column = table.Columns[i];
if(column.Name != VersionNoField)
{
WriteLine("[DataMember]");
WriteLine("public Guid {0};",column.Name);
}
}
PopIndent();
WriteLine("}");
PopIndent();
WriteLine("}");
return this.GenerationEnvironment.ToString();
}
}
#>
Generator
代码语言:javascript复制<#@ import namespace="System.Collections.Generic" #>
<#@ include file="ProcedureTemplate.tt" #>
<#@ include file="T4Toolbox.tt" #>
<#
public class ProcedureGenerator : Generator
{
public List<ProcedureTemplate> Templates{get; private set;}
public ProcedureGenerator(string databaseName, params string[] tableNames)
{
if(null == tableNames || tableNames.Length == 0)
{
throw new ArgumentNullException("数据表名有误");
}
Templates = new List<ProcedureTemplate>();
foreach(string tableName in tableNames)
{
var t = new ProcedureTemplate(databaseName, tableName);
Templates.Add(t);
}
}
protected override void RunCore()
{
foreach(ProcedureTemplate tempalte in this.Templates)
{
tempalte.RenderToFile(tempalte.GetProcedureName() ".cs");
}
}
}
#>
生成器
代码语言:javascript复制<#@ template language="C#" hostSpecific="true" debug="true" #>
<#@ include file="ProcedureGenerator.tt" #>
<#
var tableNames = new string[]{"aa","bb"};
new ProcedureGenerator("testDb",tableNames).Run();
#>
此文参考了artech的文章
http://www.cnblogs.com/artech/archive/2010/11/17/CodeGeneration.html