建立T4模板方法:右键添加新项->文本模板
使用T4模板生成Dal层代码如下:
<#@ 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); //修改当前tt模板相对应的edmx模型的位置 string inputFile = @"..\\Heima7.OA.Model\\DataModel.edmx"; EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile); string namespaceName = code.VsNamespaceSuggestion(); EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this); #> using Heima7.OA.Model; namespace Heima7.OA.EFDAL { <# foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) { #> public partial class <#=entity.Name#>Dal :BaseDal<<#=entity.Name#>>,IDAL.I<#=entity.Name#>Dal { } <#}#> }
ZJ:找规律,然后利用<#= #>把代码嵌套进去。
以上是对【利用了ADO.NET实体数据模型项目的】一些总结,T4不仅可以这样玩,还可以直接连接数据库,然后根据数据库里面的表自动生成相对应的实体类,可怕吧,哈哈,后面文章有讲解~