T4模板根据DB生成实体类
2018-06-17 21:49:37来源:未知 阅读 ()
1.前言
为什么会有这篇文章了,最近看到了一些框架,里面要写的代码太多了,故此就想偷懒,要是能写出一个T4模板,在数据库添加表后,根据模板就可以自动生成了类文件了,这样多好,心动不如行动。记得使用T4模板还是2年前,那个时候听波波老师讲课做我们的最后一个大项目CRM,简简单单的写了一下模板,保存一下,所有的类文件就出来了,当时那个膜拜,油然而生。
同时在工作中,我们公司自己开发的一个ORM,实体类都要自己写,一个数据库表的字段太多,写的真是手抽筋。如果你对T4基础语法不是很了解,可以参考我前面写的一篇文章 T4语法快速入门。
2.原理
我们要做的事情是通过数据库表生成实体类。
第一步 我们要查询出当前用户下的所有数据库表。
第二步 查询出数据库表的结构,比如字段的名称,字段的类型,字段的长度大小,是否为空等等。
工作中oracle用的比较多,在这里我就分析oracle和mssql
3.oracle
查询当前用户所有的表。
SELECT TABLE_NAME FROM USER_TABLES;
根据表名查询表结构数据
SELECT A.column_name 字段名, A.data_type 数据类型, A.data_length 长度, A.data_precision 整数位, A.Data_Scale 小数位, A.nullable 允许空值, A.Data_default 缺省值, B.comments 备注, A.TABLE_NAME 表名 FROM user_tab_columns A, user_col_comments B WHERE a.COLUMN_NAME = b.column_name AND A.Table_Name = B.Table_Name AND A.Table_Name = 'AFFIXINFO'
ModelAuto.ttinclude来源与网上,作用是生成一个一个单独的类文件,即xx.cs文件。
<#@ 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<Block> blocks = new List<Block>(); 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; } } } }#>
<#@ template debug="true" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Data" #> <#@ assembly name="System.Data.OracleClient" #> <#@ assembly name="System.Xml" #> <#@ import namespace="System" #> <#@ import namespace="System.Xml" #> <#@ import namespace="System.Data" #> <#@ import namespace="System.Data.OracleClient" #> <#@ import namespace="System.Collections.Generic"#> <#@ include file="ModelAuto.ttinclude"#> <# var manager2 = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #> <# ModelManager manager = new ModelManager(); List<string> list=manager.GetTableList(); #> <# foreach (var item in list) { string tableName=item; DataTable table= manager.GetTableSchema(tableName); #> <# manager2.StartBlock(tableName+".cs"); #> using System; using System.Data; using System.Data.OracleClient; namespace Model { /// <summary> /// 数据表实体类:<#= tableName #> /// </summary> [Serializable()] public class <#= tableName #> { <# foreach(DataRow row in table.Rows) { #> /// <summary> /// <#=row["备注"]#> /// </summary> public <#= manager.TransFromSqlType(row["数据类型"].ToString())#> <#=row["字段名"]#>{ get; set; } <#} #> } } <# manager2.EndBlock(); #> <# } #> <# manager2.Process(true); #> <#+ public class ModelManager { /// <summary> /// 数据库连接字符串 /// </summary> private const string CONNECTION_STRING = "Data Source=orcl;Persist Security Info=True;User ID=jjmis;Password=jjmis;Unicode=True"; /// <summary> /// 用户信息表名 /// </summary> private const string PERSONINFO_TABLE_NAME = "USERINFO"; /// <summary> /// 根据表名查询表结构信息 /// </summary> private const string SELECT_SCHEMA_BY_TABLE_NAME = @"SELECT A.column_name 字段名,
A.data_type 数据类型, A.data_length 长度, A.data_precision 整数位, A.Data_Scale 小数位, A.nullable 允许空值, A.Data_default 缺省值, B.comments 备注, A.TABLE_NAME 表名 FROM user_tab_columns A, user_col_comments B WHERE a.COLUMN_NAME = b.column_name AND A.Table_Name = B.Table_Name AND A.Table_Name = '{0}'"; /// <summary> /// 获得数据连接 /// </summary> /// <returns></returns> private OracleConnection GetConnection() { return new OracleConnection(CONNECTION_STRING); } /// <summary> /// 得到当前用户的所有表名 /// </summary> /// <returns></returns> public List<string> GetTableList() { string sql = "SELECT * FROM USER_TABLES"; DataTable dt = OracleHelper.ExecuteDataTable(sql); List<string> list = new List<string>(); if (dt!=null&&dt.Rows.Count>0) { for (int i = 0; i < dt.Rows.Count; i++) { list.Add(dt.Rows[i]["TABLE_NAME"].ToString()); } } return list; } /// <summary> /// 释放连接 /// </summary> /// <param name="con"></param> private void ReleaseConnection(OracleConnection con) { if (con != null) { if (con.State == ConnectionState.Open) { con.Close(); } } } public DataTable GetTableSchema(string tableName) { DataTable dt; using (OracleConnection con = GetConnection()) { con.Open(); OracleCommand cmd = con.CreateCommand(); cmd.CommandText = string.Format(SELECT_SCHEMA_BY_TABLE_NAME,tableName); cmd.CommandType = CommandType.Text; OracleDataAdapter adapter = new OracleDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); dt = ds.Tables[0]; } return dt; } /// <summary> /// SQL[不完善,需要的自己改造] /// </summary> /// <param name="type"></param> /// <returns></returns> public string TransFromSqlType(string type) { if (string.IsNullOrEmpty(type)) { return string.Empty; } if (string.Equals(type, "number", StringComparison.OrdinalIgnoreCase)) { return "int"; } if (string.Equals(type, "date", StringComparison.OrdinalIgnoreCase)) { return "DateTime"; } else if (string.Equals(type, "nvarchar2", StringComparison.OrdinalIgnoreCase)) { return "string"; } return "string"; } } #> <#+ public class OracleHelper { private static string oracleConnectionStr = "Data Source=orcl;Persist Security Info=True;User ID=jjmis;Password=jjmis;Unicode=True"; public static DataTable ExecuteDataTable(string sql, params OracleParameter[] paramList) { using (OracleConnection conn = new OracleConnection(oracleConnectionStr)) { conn.Open(); using (OracleCommand command = conn.CreateCommand()) { command.CommandText = sql; command.Parameters.AddRange(paramList); DataTable dt = new DataTable(); OracleDataAdapter adapter = new OracleDataAdapter(command); adapter.Fill(dt); return dt; } } } public static int ExecuteNonQuery(string sql, params OracleParameter[] paramList) { using (OracleConnection conn = new OracleConnection(oracleConnectionStr)) { conn.Open(); using (OracleCommand command = conn.CreateCommand()) { command.CommandText = sql; command.Parameters.AddRange(paramList); return command.ExecuteNonQuery(); } } } public static object ExecuteScalar(string sql, params OracleParameter[] paramList) { using (OracleConnection conn = new OracleConnection(oracleConnectionStr)) { conn.Open(); using (OracleCommand command = conn.CreateCommand()) { command.CommandText = sql; command.Parameters.AddRange(paramList); return command.ExecuteScalar(); } } } } #>
保存此模板文件就可以生成下面类文件。
4.Mssql
查询数据库表
string connectionString = "Data Source=.;Initial Catalog=NFineBase;User ID=sa;Password=hjf19870810;"; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); System.Data.DataTable schema = conn.GetSchema("TABLES");
通过数据库表查询表结构
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'
同样我们要生成多个类文件,需要引入 ModelAuto.ttinclude
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 = "Data Source=.;Initial Catalog=NFineBase;User ID=sa;Password=hjf19870810;"; 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"); #> //----------<#=row["TABLE_NAME"].ToString()#>开始---------- using System; namespace MyProject.Entities { /// <summary> /// 数据表实体类:<#= row["TABLE_NAME"].ToString() #> /// </summary> [Serializable()] 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); #> /// <summary> /// <#= dc.DataType.Name #>:<#=ds2.Tables[0].Rows[0].ItemArray[2]#> /// </summary> public <#= dc.DataType.Name #> <#= dc.ColumnName #> {get;set;} <# } #> } } //----------<#=row["TABLE_NAME"].ToString()#>结束---------- <# manager.EndBlock(); #> <# } #> <# manager.Process(true); #>
保存ModelTemplate.tt就可以得到类文件。
文章中的源代码在此次下载。
1.T4语法快速入门
2.T4模板根据DB生成实体类
3.NFine框架的T4模板
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- 关于laravel后台模板laravel-admin select框的使用详解 2019-10-08
- PHP迭代器和生成器用法实例分析 2019-09-30
- Swagger 生成 PHP API 接口文档详细步骤 2019-09-23
- PHP生成带有logo和底图的支付二维码 2019-08-29
- Session的生成机制、回收机制和存储机制详解 2019-08-26
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash