爲何會有這篇文章了,最近看到了一些框架,裏面要寫的代碼太多了,故此就想偷懶,要是能寫出一個T4模板,在數據庫添加表後,根據模板就能夠自動生成了類文件了,這樣多好,心動不如行動。記得使用T4模板仍是2年前,那個時候聽波波老師講課作咱們的最後一個大項目CRM,簡簡單單的寫了一下模板,保存一下,全部的類文件就出來了,當時那個膜拜,油然而生。html
同時在工做中,咱們公司本身開發的一個ORM,實體類都要本身寫,一個數據庫表的字段太多,寫的真是手抽筋。若是你對T4基礎語法不是很瞭解,能夠參考我前面寫的一篇文章 T4語法快速入門。sql
咱們要作的事情是經過數據庫表生成實體類。數據庫
第一步 咱們要查詢出當前用戶下的全部數據庫表。oracle
第二步 查詢出數據庫表的結構,好比字段的名稱,字段的類型,字段的長度大小,是否爲空等等。app
工做中oracle用的比較多,在這裏我就分析oracle和mssql框架
查詢當前用戶全部的表。ide
SELECT TABLE_NAME FROM USER_TABLES;
根據表名查詢表結構數據ui
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文件。this
<#@ 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(); } } } } #>
保存此模板文件就能夠生成下面類文件。spa
查詢數據庫表
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就能夠獲得類文件。