1、T4模板语法

<#@ template language="C#v3.5" hostSpecific="true" debug="true" #>
这里可以指定模板使用的语言,hostSpecific="true"表示是否使用特定的host(Kalman Studio里面使用的是TableHost对象,必须实现接口ITextTemplatingEngineHost)

<#@ output extension=".cs" #>  指定生成文件的扩展名

<#@ assembly name="System.Data" #>
添加程序集引用,如果要使用第三方程序集,那么最好在项目中添加引用,或者加入到GAC

<#@ import namespace="System.Data" #>
导入要使用的命名空间,注意:这里的命名空间必须要在前面指定的程序集里面找得到的,比如我指定命名空间"System.Data","System.Data.Common",这些在程序集System.Data中都有的

<#@ include file="test.tt" #> 导入模板,类似Html的include用法

<#   #>  定义代码块

<#= #>  定义表达式

<#+ #>  定义变量

 
2、生成T4模板Demo
 
<#@ template language ="C#" debug="false" hostspecific= "true"#>
<#@ include file ="EF.Utility.CS.ttinclude"#>
<#@ output extension =".cs"#>
 
<#
CodeGenerationTools code = new CodeGenerationTools( this);
MetadataLoader loader = new MetadataLoader( this);
CodeRegion region = new CodeRegion( this, 1);
MetadataTools ef = new MetadataTools( this);
 
string inputFile = @"..\\T4Demo.Model\\DataModel.edmx" ;//指定EF模型与当前T4模板的相对路径,从而找到相关的实体类
 
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();
 
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create( this);
 
#>
using T4Demo.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace T4Demo.IDAL
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))//循环遍历获取相关的实体类
#>           
     //动态生成的模板
                 public partial interface I<#= entity.Name#>Dal : IBaseDal< <#=entity.Name#> >
    {
      
    }  
<#} #>             
}
初学T4模板,有不对的还请指正。。。
posted on 2013-10-18 23:43  伊人撩月  阅读(726)  评论(0编辑  收藏  举报