本文转自:http://www.cnblogs.com/guomingfeng/p/mvc-ef-t4.htmlhtml
1、前言缓存
2、工具准备架构
3、T4代码生成预热mvc
(一) 单文件生成:HelloWorld.csapp
(二) 多文件生成框架
4、生成数据层实体相关类似代码ide
(一) 生成准备svn
(二) 生成实体相关类似代码函数
5、源码获取工具
通过前面EF的《第一篇》与《第二篇》,咱们的数据层功能已经较为完善了,但有很多代码类似度较高,好比负责实体映射的 EntityConfiguration,负责仓储操做的IEntityRepository与EntityRepository。并且每添加一个实体类型,就要手动去添加一套相应的代码,也是比较累的工做。若是能有一个根据实体类型自动生成这些类似度较高的代码的解决方案,那将会减小大量的无聊的工做。
VS提供的“文本模板”(俗称T4)功能,就是一个较好的解决方案。要添加一个实体类型,只要把实体类型定义好,而后运行一下定义好的T4模板,就能够自动生成相应的类文件。
为了更好的使用 T4模板 功能,咱们须要给VS安装以下两个插件:
下面,咱们先来体验一个最简单的T4代码生成功能,输出一个最简单的类文件。
首先,在 GMF.Demo.Core.Data中 添加一个名为 T4 的文件夹,用于存放生成本工程内的代码的T4模板文件。并在其中添加一个名为 HelloWorld.tt的“文本模板”的项。
HelloWorld.tt定义以下:
1 <#@ template debug="false" hostspecific="false" language="C#" #> 2 <#@ assembly name="System.Core" #> 3 <#@ import namespace="System.Linq" #> 4 <#@ import namespace="System.Text" #> 5 <#@ import namespace="System.Collections.Generic" #> 6 <#@ output extension=".cs" #> 7 using System; 8 9 namespace GMF.Demo.Core.Data.T4 10 { 11 public class HelloWorld 12 { 13 private string _word; 14 15 public HelloWorld(string word) 16 { 17 _word = word; 18 } 19 } 20 }
直接保存文件(T4的生成将会在保存模板,模板失去焦点等状况下自动触发生成。),将会在模板的当前位置生成一个同名的类文件:
HelloWorld.cs的内容以下:
1 using System; 2 3 namespace GMF.Demo.Core.Data.T4 4 { 5 public class HelloWorld 6 { 7 private string _word; 8 9 public HelloWorld(string word) 10 { 11 _word = word; 12 } 13 } 14 }
这样,咱们的HelloWorld之旅就结束了,很是简单。
当前位置方案的方案只能生成以下所示的代码:
生成的文件会与T4模板在同一目录中,这里就不详述了,能够参考 蒋金楠 一个简易版的T4代码生成"框架" 。
本项目的多文件须要生成到指定文件夹中,但又想对T4模板进行统一的管理,T4文件夹里放置T4模板文件,但生成的映射文件EntityConfiguration将放置到文件夹Configurations中,仓储操做的文件IEntityRepository与EntityRepository将放置到Repositories文件夹中。且生成的代码文件应能自动的添加到解决方案中,而不是只是在文件夹中存在。
要实现此需求,一个简单的办法就是经过 T4 Toolbox 来进行生成。想了解 T4 Toolbox 的细节,能够本身使用 ILSpy 来对 T4Toolbox.dll 文件进行反编译来查看源代码,若是是经过 T4 Toolbox 是经过VS的插件来安装的,将在“C:\Users\Administrator\AppData\Local\Microsoft\VisualStudio\11.0\Extensions\dca4f0lt.jdx”文件夹中(个人机器上)。下面,咱们直接进行多文件生成的演示。
首先,添加一个名为 HelloWorldTemplate.tt 的 T4 Toolbox 的代码模板。
此模板将继承于 T4 Toolbox 的 CSharpTemplate 类:
1 <#+ 2 // <copyright file="HelloWorldTemplate.tt" company="郭明锋@中国"> 3 // Copyright © 郭明锋@中国. All Rights Reserved. 4 // </copyright> 5 6 public class HelloWorldTemplate : CSharpTemplate 7 { 8 private string _className; 9 10 public HelloWorldTemplate(string className) 11 { 12 _className = className; 13 } 14 15 public override string TransformText() 16 { 17 #> 18 using System; 19 20 namespace GMF.Demo.Core.Data.T4 21 { 22 public class <#=_className #> 23 { 24 private string _word; 25 26 public <#=_className #>(string word) 27 { 28 _word = word; 29 } 30 } 31 } 32 <#+ 33 return this.GenerationEnvironment.ToString(); 34 } 35 } 36 #>
模板类中定义了一个 className 参数,用于接收一个表示要生成的类名的值。全部生成类的代码都以字符串的形式写在重写的 TransformText 方法中。
再定义一个T4模板文件 HelloWorldMulti.tt,用于调用 上面定义的代码模板进行代码文件的生成。
1 <#@ template debug="false" hostspecific="false" language="C#" #> 2 <#@ assembly name="System.Core" #> 3 <#@ import namespace="System.IO" #> 4 <#@ import namespace="System.Linq" #> 5 <#@ import namespace="System.Text" #> 6 <#@ import namespace="System.Collections.Generic" #> 7 <#@ include file="T4Toolbox.tt" #> 8 <#@ include file="HelloWorldTemplate.tt" #> 9 <# 10 string curPath = Path.GetDirectoryName(Host.TemplateFile); 11 string destPath = Path.Combine(curPath, "outPath"); 12 if(!Directory.Exists(destPath)) 13 { 14 Directory.CreateDirectory(destPath); 15 } 16 string[] classNames = new[]{"HelloWorld1", "HelloWorld2", "HelloWorld3"}; 17 foreach(string className in classNames) 18 { 19 HelloWorldTemplate template = new HelloWorldTemplate(className); 20 string fileName = string.Format(@"{0}\{1}.cs", destPath, className); 21 template.Output.Encoding = Encoding.UTF8; 22 template.RenderToFile(fileName); 23 } 24 #>
以上是整个T4模板的执行方,在执行方中,要引用全部须要用到的类库文件,命名空间,包含的模板文件等。
最后,文件的生成是调用 T4 Toolbox 的Template基类中定义的 RenderToFile(string filename)方法来生成各个文件的,输入的参数为生成文件的文件全名。在这里,生成将以下所示:
outPPath文件夹中生成了 HelloWorld1.cs、HelloWorld2.cs、HelloWorld3.cs 文件,而 HelloWorldMulti.tt 所在文件夹中也会生成一个空的 HelloWorldMulti.cs 类文件。
咱们的生成代码是彻底依赖于业务实体的,因此,须要有一个类来对业务实体的信息进行提取封装。
1 namespace GMF.Component.Tools.T4 2 { 3 /// <summary> 4 /// T4实体模型信息类 5 /// </summary> 6 public class T4ModelInfo 7 { 8 /// <summary> 9 /// 获取 模型所在模块名称 10 /// </summary> 11 public string ModuleName { get; private set; } 12 13 /// <summary> 14 /// 获取 模型名称 15 /// </summary> 16 public string Name { get; private set; } 17 18 /// <summary> 19 /// 获取 模型描述 20 /// </summary> 21 public string Description { get; private set; } 22 23 public IEnumerable<PropertyInfo> Properties { get; private set; } 24 25 public T4ModelInfo(Type modelType) 26 { 27 var @namespace = modelType.Namespace; 28 if (@namespace == null) 29 { 30 return; 31 } 32 var index = @namespace.LastIndexOf('.') + 1; 33 ModuleName = @namespace.Substring(index, @namespace.Length - index); 34 Name = modelType.Name; 35 var descAttributes = modelType.GetCustomAttributes(typeof(DescriptionAttribute), true); 36 Description = descAttributes.Length == 1 ? ((DescriptionAttribute)descAttributes[0]).Description : Name; 37 Properties = modelType.GetProperties(); 38 } 39 } 40 }
另外,经过模板生成的代码,与咱们手写的代码有以下几个区别:
基于以上几个区别,我提出以下解决方案,来解决生成代码的修改问题
实体映射配置类模板 EntityConfigurationTemplate.tt 定义:
1 <#+ 2 // <copyright file="EntityConfigurationTemplate.tt" company="郭明锋@中国"> 3 // Copyright © 郭明锋@中国. All Rights Reserved. 4 // </copyright> 5 6 public class EntityConfigurationTemplate : CSharpTemplate 7 { 8 private T4ModelInfo _model; 9 10 public EntityConfigurationTemplate(T4ModelInfo model) 11 { 12 _model = model; 13 } 14 15 /// <summary> 16 /// 获取 生成的文件名,根据模型名定义 17 /// </summary> 18 public string FileName 19 { 20 get 21 { 22 return string.Format("{0}Configuration.generated.cs", _model.Name); 23 } 24 } 25 26 public override string TransformText() 27 { 28 #> 29 //------------------------------------------------------------------------------ 30 // <auto-generated> 31 // 此代码由工具生成。 32 // 对此文件的更改可能会致使不正确的行为,而且若是 33 // 从新生成代码,这些更改将会丢失。 34 // 如存在本生成代码外的新需求,请在相同命名空间下建立同名分部类实现 <#= _model.Name #>ConfigurationAppend 分部方法。 35 // </auto-generated> 36 // 37 // <copyright file="<#= _model.Name #>Configuration.generated.cs"> 38 // Copyright(c)2013 GMFCN.All rights reserved. 39 // CLR版本:4.0.30319.239 40 // 开发组织:郭明锋@中国 41 // 公司网站:http://www.gmfcn.net 42 // 所属工程:GMF.Demo.Core.Data 43 // 生成时间:<#= DateTime.Now.ToString("yyyy-MM-dd HH:mm") #> 44 // </copyright> 45 //------------------------------------------------------------------------------ 46 47 using System; 48 using System.Data.Entity.ModelConfiguration; 49 using System.Data.Entity.ModelConfiguration.Configuration; 50 51 using GMF.Component.Data; 52 using GMF.Demo.Core.Models; 53 54 55 namespace GMF.Demo.Core.Data.Configurations 56 { 57 /// <summary> 58 /// 实体类-数据表映射——<#= _model.Description #> 59 /// </summary> 60 internal partial class <#= _model.Name #>Configuration : EntityTypeConfiguration<<#= _model.Name #>>, IEntityMapper 61 { 62 /// <summary> 63 /// 实体类-数据表映射构造函数——<#= _model.Description #> 64 /// </summary> 65 public <#= _model.Name #>Configuration() 66 { 67 <#= _model.Name #>ConfigurationAppend(); 68 } 69 70 /// <summary> 71 /// 额外的数据映射 72 /// </summary> 73 partial void <#= _model.Name #>ConfigurationAppend(); 74 75 /// <summary> 76 /// 将当前实体映射对象注册到当前数据访问上下文实体映射配置注册器中 77 /// </summary> 78 /// <param name="configurations">实体映射配置注册器</param> 79 public void RegistTo(ConfigurationRegistrar configurations) 80 { 81 configurations.Add(this); 82 } 83 } 84 } 85 <#+ 86 return this.GenerationEnvironment.ToString(); 87 } 88 } 89 #>
生成模板调用方 EntityCodeScript.tt 定义
1 <#@ template language="C#" debug="True" #> 2 <#@ output extension="cs" #> 3 <#@ Assembly Name="System.Core" #> 4 <#@ Assembly Name="$(SolutionDir)\GMF.Component.Tools\bin\Debug\GMF.Component.Tools.dll" #> 5 <#@ import namespace="System.IO" #> 6 <#@ Import Namespace="System.Linq" #> 7 <#@ Import Namespace="System.Text" #> 8 <#@ import namespace="System.Reflection" #> 9 <#@ Import Namespace="System.Collections.Generic" #> 10 <#@ Import Namespace="GMF.Component.Tools" #> 11 <#@ Import Namespace="GMF.Component.Tools.T4" #> 12 <#@ include file="T4Toolbox.tt" #> 13 <#@ include file="Include\EntityConfigurationTemplate.tt" #> 14 <# 15 string currentPath = Path.GetDirectoryName(Host.TemplateFile); 16 string projectPath =currentPath.Substring(0, currentPath.IndexOf(@"\T4")); 17 string solutionPath = currentPath.Substring(0, currentPath.IndexOf(@"\GMF.Demo.Core.Data")); 18 19 string modelFile= Path.Combine(solutionPath, @"GMF.Demo.Core.Models\bin\Debug\GMF.Demo.Core.Models.dll"); 20 byte[] fileData= File.ReadAllBytes(modelFile); 21 Assembly assembly = Assembly.Load(fileData); 22 IEnumerable<Type> modelTypes = assembly.GetTypes().Where(m => typeof(Entity).IsAssignableFrom(m) && !m.IsAbstract); 23 foreach(Type modelType in modelTypes) 24 { 25 T4ModelInfo model = new T4ModelInfo(modelType); 26 //实体映射类 27 EntityConfigurationTemplate config = new EntityConfigurationTemplate(model); 28 string path = string.Format(@"{0}\Configurations", projectPath); 29 config.Output.Encoding = Encoding.UTF8; 30 config.RenderToFile(Path.Combine(path, config.FileName)); 31 } 32 #>
调用方经过反射从业务实体程序集 GMF.Demo.Core.Models.dll 中获取全部基类为 Entity 的而且不是抽象类的实体类型信息,再调用模板逐个生成实体配置类文件。
例如,生成的登陆记录信息(LoginLog)的映射文件 LoginLogConfiguration.generated.cs 以下:
1 //------------------------------------------------------------------------------ 2 // <auto-generated> 3 // 此代码由工具生成。 4 // 对此文件的更改可能会致使不正确的行为,而且若是 5 // 从新生成代码,这些更改将会丢失。 6 // 如存在本生成代码外的新需求,请在相同命名空间下建立同名分部类实现 LoginLogConfigurationAppend 分部方法。 7 // </auto-generated> 8 // 9 // <copyright file="LoginLogConfiguration.generated.cs"> 10 // Copyright(c)2013 GMFCN.All rights reserved. 11 // CLR版本:4.0.30319.239 12 // 开发组织:郭明锋@中国 13 // 公司网站:http://www.gmfcn.net 14 // 所属工程:GMF.Demo.Core.Data 15 // 生成时间:2013-06-16 17:45 16 // </copyright> 17 //------------------------------------------------------------------------------ 18 19 using System; 20 using System.Data.Entity.ModelConfiguration; 21 using System.Data.Entity.ModelConfiguration.Configuration; 22 23 using GMF.Component.Data; 24 using GMF.Demo.Core.Models; 25 26 27 namespace GMF.Demo.Core.Data.Configurations 28 { 29 /// <summary> 30 /// 实体类-数据表映射——登陆记录信息 31 /// </summary> 32 internal partial class LoginLogConfiguration : EntityTypeConfiguration<LoginLog>, IEntityMapper 33 { 34 /// <summary> 35 /// 实体类-数据表映射构造函数——登陆记录信息 36 /// </summary> 37 public LoginLogConfiguration() 38 { 39 LoginLogConfigurationAppend(); 40 } 41 42 /// <summary> 43 /// 额外的数据映射 44 /// </summary> 45 partial void LoginLogConfigurationAppend(); 46 47 /// <summary> 48 /// 将当前实体映射对象注册到当前数据访问上下文实体映射配置注册器中 49 /// </summary> 50 /// <param name="configurations">实体映射配置注册器</param> 51 public void RegistTo(ConfigurationRegistrar configurations) 52 { 53 configurations.Add(this); 54 } 55 } 56 }
要配置登陆信息与用户信息的 N:1 关系,只须要添加一个分部类 LoginLogConfiguration,并实现分类方法 LoginLogConfigurationAppend 便可。
1 namespace GMF.Demo.Core.Data.Configurations 2 { 3 partial class LoginLogConfiguration 4 { 5 partial void LoginLogConfigurationAppend() 6 { 7 HasRequired(m => m.Member).WithMany(n => n.LoginLogs); 8 } 9 } 10 }
实体映射配置类模板 EntityConfigurationTemplate.tt 定义:
1 <#+ 2 // <copyright file="IEntityRepositoryTemplate.tt" company="郭明锋@中国"> 3 // Copyright © 郭明锋@中国. All Rights Reserved. 4 // </copyright> 5 6 public class IEntityRepositoryTemplate : CSharpTemplate 7 { 8 private T4ModelInfo _model; 9 10 public IEntityRepositoryTemplate(T4ModelInfo model) 11 { 12 _model = model; 13 } 14 15 /// <summary> 16 /// 获取 生成的文件名,根据模型名定义 17 /// </summary> 18 public string FileName 19 { 20 get 21 { 22 return string.Format("I{0}Repository.generated.cs", _model.Name); 23 } 24 } 25 26 public override string TransformText() 27 { 28 #> 29 //------------------------------------------------------------------------------ 30 // <auto-generated> 31 // 此代码由工具生成。 32 // 对此文件的更改可能会致使不正确的行为,而且若是 33 // 从新生成代码,这些更改将会丢失。 34 // 如存在本生成代码外的新需求,请在相同命名空间下建立同名分部类进行实现。 35 // </auto-generated> 36 // 37 // <copyright file="I<#= _model.Name #>Repository.generated.cs"> 38 // Copyright(c)2013 GMFCN.All rights reserved. 39 // CLR版本:4.0.30319.239 40 // 开发组织:郭明锋@中国 41 // 公司网站:http://www.gmfcn.net 42 // 所属工程:GMF.Demo.Core.Data 43 // 生成时间:<#= DateTime.Now.ToString("yyyy-MM-dd HH:mm") #> 44 // </copyright> 45 //------------------------------------------------------------------------------ 46 47 using System; 48 49 using GMF.Component.Data; 50 using GMF.Demo.Core.Models; 51 52 53 namespace GMF.Demo.Core.Data.Repositories 54 { 55 /// <summary> 56 /// 数据访问层接口——<#= _model.Description #> 57 /// </summary> 58 public partial interface I<#= _model.Name #>Repository : IRepository<<#= _model.Name #>> 59 { } 60 } 61 62 <#+ 63 return this.GenerationEnvironment.ToString(); 64 } 65 } 66 #>
相应的,在调用方 EntityCodeScript.tt 中添加模板调用代码(以下 11-15 行所示):
1 foreach(Type modelType in modelTypes) 2 { 3 T4ModelInfo model = new T4ModelInfo(modelType); 4 5 //实体映射类 6 EntityConfigurationTemplate config = new EntityConfigurationTemplate(model); 7 string path = string.Format(@"{0}\Configurations", projectPath); 8 config.Output.Encoding = Encoding.UTF8; 9 config.RenderToFile(Path.Combine(path, config.FileName)); 10 11 //实体仓储操做接口 12 IEntityRepositoryTemplate irep= new IEntityRepositoryTemplate(model); 13 path = string.Format(@"{0}\Repositories", projectPath); 14 irep.Output.Encoding = Encoding.UTF8; 15 irep.RenderToFile(Path.Combine(path, irep.FileName)); 16 }
生成的登陆记录信息仓储操做接口 ILoginLogRepository.generated.cs:
1 //------------------------------------------------------------------------------ 2 // <auto-generated> 3 // 此代码由工具生成。 4 // 对此文件的更改可能会致使不正确的行为,而且若是 5 // 从新生成代码,这些更改将会丢失。 6 // 如存在本生成代码外的新需求,请在相同命名空间下建立同名分部类进行实现。 7 // </auto-generated> 8 // 9 // <copyright file="ILoginLogRepository.generated.cs"> 10 // Copyright(c)2013 GMFCN.All rights reserved. 11 // CLR版本:4.0.30319.239 12 // 开发组织:郭明锋@中国 13 // 公司网站:http://www.gmfcn.net 14 // 所属工程:GMF.Demo.Core.Data 15 // 生成时间:2013-06-16 17:56 16 // </copyright> 17 //------------------------------------------------------------------------------ 18 19 using System; 20 21 using GMF.Component.Data; 22 using GMF.Demo.Core.Models; 23 24 25 namespace GMF.Demo.Core.Data.Repositories 26 { 27 /// <summary> 28 /// 数据访问层接口——登陆记录信息 29 /// </summary> 30 public partial interface ILoginLogRepository : IRepository<LoginLog> 31 { } 32 }
若是 IRepository<T> 中定义的仓储操做不知足登陆记录仓储操做的需求,只须要添加一个相应的分部接口,在其中进行需求的定义便可。这里当前没有额外的需求,就不须要额外定义了。
实体仓储操做的实现与仓储操做接口相似,这里略过。
完成生成后,代码结构以下所示:
若是添加了或者删除了一个实体,只须要从新运行一下调用模板 EntityCodeScript.tt 便可从新生成新的代码。
为了让你们能第一时间获取到本架构的最新代码,也为了方便我对代码的管理,本系列的源码已加入微软的开源项目网站 http://www.codeplex.com,地址为:
https://gmframework.codeplex.com/
能够经过下列途径获取到最新代码:
本文版权归做者和博客园共有,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文链接,不然保留追究法律责任的权利。