博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
T4生成实体
阅读量:6006 次
发布时间:2019-06-20

本文共 6632 字,大约阅读时间需要 22 分钟。

hot3.png

新建一个一般应用程序 新建一个文本模版 ModelTemplate.tt, 内容如下

<#@ template language="C#" debug="True" hostspecific="True" #><#@ output extension=".cs" #><#@ assembly name="System.Data" #><#@ assembly name="System.xml" #><#@ import namespace="System.Collections.Generic" #><#@ import namespace="System.Data.SqlClient" #><#@ import namespace="System.Data" #><#@ include file="ModelAuto.ttinclude"#><# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #><# 	string connectionString = "数据库连接字符串";     SqlConnection conn = new SqlConnection(connectionString);     conn.Open();     System.Data.DataTable schema = conn.GetSchema("TABLES");     string selectQuery = "select * from @tableName";     SqlCommand command = new SqlCommand(selectQuery,conn);     SqlDataAdapter ad = new SqlDataAdapter(command);     System.Data.DataSet ds = new DataSet();     string propQuery = "SELECT 表名=sobj.name,字段名=scol.name,字段说明=sprop.[value] FROM syscolumns as scol inner join sys.sysobjects as sobj on scol.id=sobj.id and sobj.xtype='U' and sobj.name<>'dtproperties' left join sys.extended_properties as sprop on scol.id=sprop.major_id and scol.colid=sprop.minor_id where sobj.name='@tableName' and scol.name='@columnName'";     SqlCommand command2 = new SqlCommand(propQuery,conn);     SqlDataAdapter ad2 = new SqlDataAdapter(command2);     System.Data.DataSet ds2 = new DataSet(); #><# foreach(System.Data.DataRow row in schema.Rows) {  #>        <# 	manager.StartBlock(row["TABLE_NAME"]+".cs");	#>using System;namespace MyProject.Entities {     public class <#= row["TABLE_NAME"].ToString() #>    {    		<#        ds.Tables.Clear();        command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString());         ad.FillSchema(ds, SchemaType.Mapped, row["TABLE_NAME"].ToString());        foreach (DataColumn dc in ds.Tables[0].Columns)        {         #>        <#             ds2.Tables.Clear();            command2.CommandText = propQuery.Replace("@tableName",row["TABLE_NAME"].ToString());             command2.CommandText = command2.CommandText.Replace("@columnName",dc.ColumnName);             ad2.Fill(ds2);        #> 		/// 		/// <#=ds2.Tables[0].Rows[0].ItemArray[2]#>		///                        		public <#= dc.DataType.Name #> <#= dc.ColumnName #> {get;set;}           <# }  #>       }    }	  	<# manager.EndBlock(); #><#     } #> <#    manager.Process(true);#>

里面<#@ include file="ModelAuto.ttinclude"#> 文件如下:

<#@ assembly name="System.Core"#><#@ assembly name="EnvDTE"#><#@ import namespace="System.Collections.Generic"#><#@ import namespace="System.IO"#><#@ import namespace="System.Text"#><#@ import namespace="Microsoft.VisualStudio.TextTemplating"#><#+class Manager{    public struct Block {        public String Name;        public int Start, Length;    }    public List
blocks = new List
(); public Block currentBlock; public Block footerBlock = new Block(); public Block headerBlock = new Block(); public ITextTemplatingEngineHost host; public ManagementStrategy strategy; public StringBuilder template; public String OutputPath { get; set; } public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader) { this.host = host; this.template = template; OutputPath = String.Empty; strategy = ManagementStrategy.Create(host); } public void StartBlock(String name) { currentBlock = new Block { Name = name, Start = template.Length }; } public void StartFooter() { footerBlock.Start = template.Length; } public void EndFooter() { footerBlock.Length = template.Length - footerBlock.Start; } public void StartHeader() { headerBlock.Start = template.Length; } public void EndHeader() { headerBlock.Length = template.Length - headerBlock.Start; } public void EndBlock() { currentBlock.Length = template.Length - currentBlock.Start; blocks.Add(currentBlock); } public void Process(bool split) { String header = template.ToString(headerBlock.Start, headerBlock.Length); String footer = template.ToString(footerBlock.Start, footerBlock.Length); blocks.Reverse(); foreach(Block block in blocks) { String fileName = Path.Combine(OutputPath, block.Name); if (split) { String content = header + template.ToString(block.Start, block.Length) + footer; strategy.CreateFile(fileName, content); template.Remove(block.Start, block.Length); } else { strategy.DeleteFile(fileName); } } }}class ManagementStrategy{ internal static ManagementStrategy Create(ITextTemplatingEngineHost host) { return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host); } internal ManagementStrategy(ITextTemplatingEngineHost host) { } internal virtual void CreateFile(String fileName, String content) { File.WriteAllText(fileName, content); } internal virtual void DeleteFile(String fileName) { if (File.Exists(fileName)) File.Delete(fileName); }}class VSManagementStrategy : ManagementStrategy{ private EnvDTE.ProjectItem templateProjectItem; internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) { IServiceProvider hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) throw new ArgumentNullException("Could not obtain hostServiceProvider"); EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE)); if (dte == null) throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile); } internal override void CreateFile(String fileName, String content) { base.CreateFile(fileName, content); ((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null); } internal override void DeleteFile(String fileName) { ((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null); } private void FindAndDeleteFile(String fileName) { foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) { if (projectItem.get_FileNames(0) == fileName) { projectItem.Delete(); return; } } }}#>

然后保存下文本文件就会自动生成在你的项目中了

转载于:https://my.oschina.net/objectboy/blog/1538200

你可能感兴趣的文章
谈网站数据分析
查看>>
我的友情链接
查看>>
构建企业实时备份数据服务器(Rsync+inotify)
查看>>
优化Tomcat篇:调增tomcat6响应池
查看>>
无线蹭网小记
查看>>
Go笔记-数据库
查看>>
做了软件测试才知道
查看>>
Dwz做前台页面,Jfinal后台使用前台下载excel【两种解决方案】
查看>>
Android 部分截图分享
查看>>
脚本实现mysql 备份
查看>>
linux 知识点整理,从虚拟机安装到常用开发软件在linux上的安装命令
查看>>
关于WinGate代理服务器的概述
查看>>
socket, nio socket 及nio socket框架MINA总结 (转)
查看>>
R语言笔记
查看>>
linux “洪ping”
查看>>
健康传说网简介
查看>>
学校宿舍的深夜之思考
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
mysql prepare语句使用
查看>>