生活随笔
收集整理的這篇文章主要介紹了
[转]T4模版引擎之生成数据库实体类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文轉自:http://www.cnblogs.com/lzrabbit/archive/2012/07/18/2597953.html
?
在通過T4模版引擎之基礎入門?對T4有了初步印象后,我們開始實戰篇。T4模板引擎可以當做一個代碼生成器,代碼生成器的職責當然是用來生成代碼(這不是廢話嗎)。而這其中我們使用的最普遍的是根據數據庫生成實體類。
工欲善其事必先利其器,在這之前先來介紹一款T4編輯器T4 Editor,我們可以點擊鏈接去下載然后安裝,不過還是推薦大家直接在VS擴展管理器里直接安裝來的方便 工具->擴展管理器->聯機庫 搜索 "T4 Editor",選擇第一項 "tangible T4 Editor 2.0 plus modeling tools for VS2010" 進行安裝即可,如下圖所示:
安裝上T4 Editor后,編輯T4模板是就有代碼著色和智能提示了,下圖為安裝T4 Editor后的代碼著色效果,怎么樣是不是耳目一新,呵呵
?
?
接下來開始正式進入我們的主題,從數據庫自動生成實體類
新建一個控制臺項目,然后添加T4模板,這里我們起名字為Customers.tt 修改輸出文件擴展名為.cs <#@ output extension=".cs" #> 添加常用的程序集和命名空間引用 <#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Data.dll" #>
<#@ assembly name="System.Data.DataSetExtensions.dll" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #> 添加數據庫操作DbHelper引用 <#+public class DbHelper{#region GetDbTablespublic static List<DbTable> GetDbTables(string connectionString, string database, string tables = null){if (!string.IsNullOrEmpty(tables)){tables = string.Format(" and obj.name in ('{0}')", tables.Replace(",", "','"));}#region SQLstring sql = string.Format(@"SELECTobj.name tablename,schem.name schemname,idx.rows,CAST(CASE WHEN (SELECT COUNT(1) FROM sys.indexes WHERE object_id= obj.OBJECT_ID AND is_primary_key=1) >=1 THEN 1ELSE 0END AS BIT) HasPrimaryKey from {0}.sys.objects obj inner join {0}.dbo.sysindexes idx on obj.object_id=idx.id and idx.indid<=1INNER JOIN {0}.sys.schemas schem ON obj.schema_id=schem.schema_idwhere type='U' {1}order by obj.name", database, tables);#endregionDataTable dt = GetDataTable(connectionString, sql);return dt.Rows.Cast<DataRow>().Select(row => new DbTable{TableName = row.Field<string>("tablename"),SchemaName = row.Field<string>("schemname"),Rows = row.Field<int>("rows"),HasPrimaryKey = row.Field<bool>("HasPrimaryKey")}).ToList();}#endregion#region GetDbColumnspublic static List<DbColumn> GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo"){#region SQLstring sql = string.Format(@"WITH indexCTE AS(SELECT ic.column_id,ic.index_column_id,ic.object_id FROM {0}.sys.indexes idxINNER JOIN {0}.sys.index_columns ic ON idx.index_id = ic.index_id AND idx.object_id = ic.object_idWHERE idx.object_id =OBJECT_ID(@tableName) AND idx.is_primary_key=1)selectcolm.column_id ColumnID,CAST(CASE WHEN indexCTE.column_id IS NULL THEN 0 ELSE 1 END AS BIT) IsPrimaryKey,colm.name ColumnName,systype.name ColumnType,colm.is_identity IsIdentity,colm.is_nullable IsNullable,cast(colm.max_length as int) ByteLength,(case when systype.name='nvarchar' and colm.max_length>0 then colm.max_length/2 when systype.name='nchar' and colm.max_length>0 then colm.max_length/2when systype.name='ntext' and colm.max_length>0 then colm.max_length/2 else colm.max_lengthend) CharLength,cast(colm.precision as int) Precision,cast(colm.scale as int) Scale,prop.value Remarkfrom {0}.sys.columns colminner join {0}.sys.types systype on colm.system_type_id=systype.system_type_id and colm.user_type_id=systype.user_type_idleft join {0}.sys.extended_properties prop on colm.object_id=prop.major_id and colm.column_id=prop.minor_idLEFT JOIN indexCTE ON colm.column_id=indexCTE.column_id AND colm.object_id=indexCTE.object_id where colm.object_id=OBJECT_ID(@tableName)order by colm.column_id", database);#endregionSqlParameter param = new SqlParameter("@tableName", SqlDbType.NVarChar, 100) { Value = string.Format("{0}.{1}.{2}", database, schema, tableName) };DataTable dt = GetDataTable(connectionString, sql, param);return dt.Rows.Cast<DataRow>().Select(row => new DbColumn(){ColumnID = row.Field<int>("ColumnID"),IsPrimaryKey = row.Field<bool>("IsPrimaryKey"),ColumnName = row.Field<string>("ColumnName"),ColumnType = row.Field<string>("ColumnType"),IsIdentity = row.Field<bool>("IsIdentity"),IsNullable = row.Field<bool>("IsNullable"),ByteLength = row.Field<int>("ByteLength"),CharLength = row.Field<int>("CharLength"),Scale = row.Field<int>("Scale"),Remark = row["Remark"].ToString()}).ToList();}#endregion #region GetDataTablepublic static DataTable GetDataTable(string connectionString, string commandText, params SqlParameter[] parms){using (SqlConnection connection = new SqlConnection(connectionString)){SqlCommand command = connection.CreateCommand();command.CommandText = commandText;command.Parameters.AddRange(parms);SqlDataAdapter adapter = new SqlDataAdapter(command);DataTable dt = new DataTable();adapter.Fill(dt);return dt;}}#endregion}#region DbTable/// <summary>/// 表結構/// </summary>public sealed class DbTable{/// <summary>/// 表名稱/// </summary>public string TableName { get; set; }/// <summary>/// 表的架構/// </summary>public string SchemaName { get; set; }/// <summary>/// 表的記錄數/// </summary>public int Rows { get; set; }/// <summary>/// 是否含有主鍵/// </summary>public bool HasPrimaryKey { get; set; }}#endregion#region DbColumn/// <summary>/// 表字段結構/// </summary>public sealed class DbColumn{/// <summary>/// 字段ID/// </summary>public int ColumnID { get; set; }/// <summary>/// 是否主鍵/// </summary>public bool IsPrimaryKey { get; set; }/// <summary>/// 字段名稱/// </summary>public string ColumnName { get; set; }/// <summary>/// 字段類型/// </summary>public string ColumnType { get; set; }/// <summary>/// 數據庫類型對應的C#類型/// </summary>public string CSharpType{get{return SqlServerDbTypeMap.MapCsharpType(ColumnType);}}/// <summary>/// /// </summary>public Type CommonType{get{return SqlServerDbTypeMap.MapCommonType(ColumnType);}}/// <summary>/// 字節長度/// </summary>public int ByteLength { get; set; }/// <summary>/// 字符長度/// </summary>public int CharLength { get; set; }/// <summary>/// 小數位/// </summary>public int Scale { get; set; }/// <summary>/// 是否自增列/// </summary>public bool IsIdentity { get; set; }/// <summary>/// 是否允許空/// </summary>public bool IsNullable { get; set; }/// <summary>/// 描述/// </summary>public string Remark { get; set; }}#endregion#region SqlServerDbTypeMappublic class SqlServerDbTypeMap{public static string MapCsharpType(string dbtype){if (string.IsNullOrEmpty(dbtype)) return dbtype;dbtype = dbtype.ToLower();string csharpType = "object";switch (dbtype){case "bigint": csharpType = "long"; break;case "binary": csharpType = "byte[]"; break;case "bit": csharpType = "bool"; break;case "char": csharpType = "string"; break;case "date": csharpType = "DateTime"; break;case "datetime": csharpType = "DateTime"; break;case "datetime2": csharpType = "DateTime"; break;case "datetimeoffset": csharpType = "DateTimeOffset"; break;case "decimal": csharpType = "decimal"; break;case "float": csharpType = "double"; break;case "image": csharpType = "byte[]"; break;case "int": csharpType = "int"; break;case "money": csharpType = "decimal"; break;case "nchar": csharpType = "string"; break;case "ntext": csharpType = "string"; break;case "numeric": csharpType = "decimal"; break;case "nvarchar": csharpType = "string"; break;case "real": csharpType = "Single"; break;case "smalldatetime": csharpType = "DateTime"; break;case "smallint": csharpType = "short"; break;case "smallmoney": csharpType = "decimal"; break;case "sql_variant": csharpType = "object"; break;case "sysname": csharpType = "object"; break;case "text": csharpType = "string"; break;case "time": csharpType = "TimeSpan"; break;case "timestamp": csharpType = "byte[]"; break;case "tinyint": csharpType = "byte"; break;case "uniqueidentifier": csharpType = "Guid"; break;case "varbinary": csharpType = "byte[]"; break;case "varchar": csharpType = "string"; break;case "xml": csharpType = "string"; break;default: csharpType = "object"; break;}return csharpType;}public static Type MapCommonType(string dbtype){if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();dbtype = dbtype.ToLower();Type commonType = typeof(object);switch (dbtype){case "bigint": commonType = typeof(long); break;case "binary": commonType = typeof(byte[]); break;case "bit": commonType = typeof(bool); break;case "char": commonType = typeof(string); break;case "date": commonType = typeof(DateTime); break;case "datetime": commonType = typeof(DateTime); break;case "datetime2": commonType = typeof(DateTime); break;case "datetimeoffset": commonType = typeof(DateTimeOffset); break;case "decimal": commonType = typeof(decimal); break;case "float": commonType = typeof(double); break;case "image": commonType = typeof(byte[]); break;case "int": commonType = typeof(int); break;case "money": commonType = typeof(decimal); break;case "nchar": commonType = typeof(string); break;case "ntext": commonType = typeof(string); break;case "numeric": commonType = typeof(decimal); break;case "nvarchar": commonType = typeof(string); break;case "real": commonType = typeof(Single); break;case "smalldatetime": commonType = typeof(DateTime); break;case "smallint": commonType = typeof(short); break;case "smallmoney": commonType = typeof(decimal); break;case "sql_variant": commonType = typeof(object); break;case "sysname": commonType = typeof(object); break;case "text": commonType = typeof(string); break;case "time": commonType = typeof(TimeSpan); break;case "timestamp": commonType = typeof(byte[]); break;case "tinyint": commonType = typeof(byte); break;case "uniqueidentifier": commonType = typeof(Guid); break;case "varbinary": commonType = typeof(byte[]); break;case "varchar": commonType = typeof(string); break;case "xml": commonType = typeof(string); break;default: commonType = typeof(object); break;}return commonType;}}#endregion#> <#@ include file="$(ProjectDir)DbHelper.ttinclude" #> DbHelper相對比較復雜,把一些常用操作進行了簡單封裝,因此放到一個單獨的文件里面進行引用,可以方便的進行復用,這里DbHelper的后綴名使用ttinclude,這里的后綴名可以隨便起,按照微軟的建議:用于include的文件盡量不要使用.tt做后綴名
在頁面底部定義一些常用變量,以方便操作 <#+public class config{public static readonly string ConnectionString="Data Source=(local);Integrated Security=true;Initial Catalog=Northwind;";public static readonly string DbDatabase="Northwind";public static readonly string TableName="Customers";}
#> 這里我們把數據庫連接串和數據庫、表名字定義一下,方便修改和使用
最后來編寫用于實體類生成的代碼 //------------------------------------------------------------------------------
// <auto-generated>
// 此代碼由T4模板自動生成
// 生成時間 <#=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by 懶惰的肥兔
// 對此文件的更改可能會導致不正確的行為,并且如果
// 重新生成代碼,這些更改將會丟失。
// </auto-generated>
//------------------------------------------------------------------------------using System;
namespace T4ConsoleApplication.Entities
{ public class <#=config.TableName#>{<# foreach(DbColumn column in DbHelper.GetDbColumns(config.ConnectionString, config.DbDatabase, config.TableName)){#>/// <summary>/// <#=column.Remark#>/// </summary> public <#= column.CSharpType#><# if(column.CommonType.IsValueType && column.IsNullable){#>?<#}#> <#=column.ColumnName#> { get; set; }<#}#> }
} 全部完成后我們的Customers.tt文件就編寫好了 <#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Data.dll" #>
<#@ assembly name="System.Data.DataSetExtensions.dll" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ include file="$(ProjectDir)DbHelper.ttinclude" #>
//------------------------------------------------------------------------------
// <auto-generated>
// 此代碼由T4模板自動生成
// 生成時間 <#=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by 懶惰的肥兔
// 對此文件的更改可能會導致不正確的行為,并且如果
// 重新生成代碼,這些更改將會丟失。
// </auto-generated>
//------------------------------------------------------------------------------using System;
namespace T4ConsoleApplication.Entities
{ public class <#=config.TableName#>{<# foreach(DbColumn column in DbHelper.GetDbColumns(config.ConnectionString, config.DbDatabase, config.TableName)){#>/// <summary>/// <#=column.Remark#>/// </summary> public <#= column.CSharpType#><# if(column.CommonType.IsValueType && column.IsNullable){#>?<#}#> <#=column.ColumnName#> { get; set; }<#}#> }
}<#+public class config{public static readonly string ConnectionString="Data Source=(local);Integrated Security=true;Initial Catalog=Northwind;";public static readonly string DbDatabase="Northwind";public static readonly string TableName="Customers";}
#> 進行保存后會自動生成Customers.cs文件
//------------------------------------------------------------------------------
// <auto-generated>
// 此代碼由T4模板自動生成
// 生成時間 2012-07-18 17:51:26 by 懶惰的肥兔
// 對此文件的更改可能會導致不正確的行為,并且如果
// 重新生成代碼,這些更改將會丟失。
// </auto-generated>
//------------------------------------------------------------------------------using System;
namespace T4ConsoleApplication.Entities
{ public class Customers{/// <summary>/// /// </summary> public string CustomerID { get; set; }/// <summary>/// /// </summary> public string CompanyName { get; set; }/// <summary>/// /// </summary> public string ContactName { get; set; }/// <summary>/// /// </summary> public string ContactTitle { get; set; }/// <summary>/// /// </summary> public string Address { get; set; }/// <summary>/// /// </summary> public string City { get; set; }/// <summary>/// /// </summary> public string Region { get; set; }/// <summary>/// /// </summary> public string PostalCode { get; set; }/// <summary>/// /// </summary> public string Country { get; set; }/// <summary>/// /// </summary> public string Phone { get; set; }/// <summary>/// /// </summary> public string Fax { get; set; }}
} ?
至此完整演示了怎樣一步步根據數據庫生成實體類的操作,是不是很簡單,如對語法和操作不理解的地方可以參考T4模版引擎之基礎入門,稍微用心研究下,輕松打造屬于自己的代碼生成器。
本文簡單介紹了基于單個模板生成數據庫實體類的示例,離具體實用還有一定的距離,畢竟總不能為每個數據表建一個模板吧,下一篇將揭曉如何通過單個T4模板生成多個文件,以及自動生成整個數據庫的所有實體類,敬請期待
下班了,拍拍屁股走人。。。
源碼:T4ConsoleApplication.rar
注:此文章屬懶惰的肥兔原創,版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接:http://www.cnblogs.com/lzrabbit/archive/2012/07/18/2597953.html
若您覺得這篇文章還不錯請點擊下右下角的推薦,有了您的支持才能激發作者更大的寫作熱情,非常感謝。
如有問題,可以通過lzrabbit@126.com聯系我。
總結
以上是生活随笔為你收集整理的[转]T4模版引擎之生成数据库实体类的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。