T4 反射实体模型生成代码(Demo)

网友投稿 289 2022-09-28

T4 反射实体模型生成代码(Demo)

1.新建一个T4 Script

<#@ template language="C#" debug="True" #><#@ output extension="cs" #><#@ Assembly Name="System.Core" #><#@ Assembly Name="$(SolutionDir)Demo.Tools\bin\Debug\Demo.Tools.dll" #><#@ import namespace="System.IO" #><#@ Import Namespace="System.Linq" #><#@ Import Namespace="System.Text" #><#@ import namespace="System.Reflection" #><#@ Import Namespace="System.Collections.Generic" #><#@ Import Namespace="Demo.Tools" #><#@ include file="T4Toolbox.tt" #><#@ include file="EntityTemplate.tt" #><# //脚本运行路径 string currentPath = Path.GetDirectoryName(Host.TemplateFile); //解决方案路径 string solutionPath = currentPath.Substring(0, currentPath.IndexOf(@"\Demo.T4Generator\T4")); //输入文件路径 string outputPath = Path.Combine(solutionPath, @"MvcApplication1\Models"); //输出项目路径 string targetProject = Path.Combine(solutionPath, @"MvcApplication1\MvcApplication1.csproj"); //包含实体定义的DLL所在位置 string modelFile= Path.Combine(solutionPath, @"Demo.Entitys\bin\Debug\Demo.Entitys.dll"); //加载实体程序集 byte[] fileData= File.ReadAllBytes(modelFile); Assembly assembly = Assembly.Load(fileData); //反射出所有继承了Entity的实体类 IEnumerable modelTypes = assembly.GetTypes().Where(m => typeof(Demo.Tools.Entity).IsAssignableFrom(m) && !m.IsAbstract); foreach(Type modelType in modelTypes) { T4ModelInfo model = new T4ModelInfo(modelType); //实体模板 EntityConfigurationTemplate config = new EntityConfigurationTemplate(model); //输出的文件编码 config.Output.Encoding = Encoding.UTF8; //定制输出项目 config.Output.Project = targetProject; //输出生成的文件 config.RenderToFile(Path.Combine(outputPath, config.FileName)); }#>

2、新建T4 Template,这里是具体的模板

<#+public class EntityConfigurationTemplate : CSharpTemplate{ private T4ModelInfo _model; public EntityConfigurationTemplate(T4ModelInfo model) { _model = model; } ///

/// 获取 生成的文件名,根据模型名定义 /// public string FileName { get { return string.Format("{0}.generated.cs", _model.Name); } } public override string TransformText() {#>//------------------------------------------------------------------------------// // 此代码由工具生成。// 对此文件的更改可能会导致不正确的行为,并且如果// 重新生成代码,这些更改将会丢失。// //// // 生成时间:<#= DateTime.Now.ToString("yyyy-MM-dd HH:mm") #>// //------------------------------------------------------------------------------using System;using System.Data;using Demo.Entitys;namespace MvcApplication1.Models{ /// /// <#= _model.Description #> /// internal partial class <#= _model.Name #> { /// /// <#= _model.Description #> /// public <#= _model.Name #>() { <#= _model.Name #>(); } }}<#+ return this.GenerationEnvironment.ToString(); }}#>

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java中两个List之间的比较方法(差集、交集和并集)
下一篇:MD5加密解密类(asp.net)&使用MD5过时处理
相关文章

 发表评论

暂时没有评论,来抢沙发吧~