日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

[转]T4模版引擎之生成数据库实体类

發(fā)布時(shí)間:2025/3/19 数据库 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [转]T4模版引擎之生成数据库实体类 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文轉(zhuǎn)自:http://www.cnblogs.com/lzrabbit/archive/2012/07/18/2597953.html

?

在通過(guò)T4模版引擎之基礎(chǔ)入門?對(duì)T4有了初步印象后,我們開(kāi)始實(shí)戰(zhàn)篇。T4模板引擎可以當(dāng)做一個(gè)代碼生成器,代碼生成器的職責(zé)當(dāng)然是用來(lái)生成代碼(這不是廢話嗎)。而這其中我們使用的最普遍的是根據(jù)數(shù)據(jù)庫(kù)生成實(shí)體類。

  工欲善其事必先利其器,在這之前先來(lái)介紹一款T4編輯器T4 Editor,我們可以點(diǎn)擊鏈接去下載然后安裝,不過(guò)還是推薦大家直接在VS擴(kuò)展管理器里直接安裝來(lái)的方便 工具->擴(kuò)展管理器->聯(lián)機(jī)庫(kù) 搜索 "T4 Editor",選擇第一項(xiàng) "tangible T4 Editor 2.0 plus modeling tools for VS2010" 進(jìn)行安裝即可,如下圖所示:

安裝上T4 Editor后,編輯T4模板是就有代碼著色和智能提示了,下圖為安裝T4 Editor后的代碼著色效果,怎么樣是不是耳目一新,呵呵

?

?

接下來(lái)開(kāi)始正式進(jìn)入我們的主題,從數(shù)據(jù)庫(kù)自動(dòng)生成實(shí)體類

  • 新建一個(gè)控制臺(tái)項(xiàng)目,然后添加T4模板,這里我們起名字為Customers.tt

  • 修改輸出文件擴(kuò)展名為.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" #>
  • 添加數(shù)據(jù)庫(kù)操作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>/// 表結(jié)構(gòu)/// </summary>public sealed class DbTable{/// <summary>/// 表名稱/// </summary>public string TableName { get; set; }/// <summary>/// 表的架構(gòu)/// </summary>public string SchemaName { get; set; }/// <summary>/// 表的記錄數(shù)/// </summary>public int Rows { get; set; }/// <summary>/// 是否含有主鍵/// </summary>public bool HasPrimaryKey { get; set; }}#endregion#region DbColumn/// <summary>/// 表字段結(jié)構(gòu)/// </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>/// 數(shù)據(jù)庫(kù)類型對(duì)應(yīng)的C#類型/// </summary>public string CSharpType{get{return SqlServerDbTypeMap.MapCsharpType(ColumnType);}}/// <summary>/// /// </summary>public Type CommonType{get{return SqlServerDbTypeMap.MapCommonType(ColumnType);}}/// <summary>/// 字節(jié)長(zhǎng)度/// </summary>public int ByteLength { get; set; }/// <summary>/// 字符長(zhǎng)度/// </summary>public int CharLength { get; set; }/// <summary>/// 小數(shù)位/// </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相對(duì)比較復(fù)雜,把一些常用操作進(jìn)行了簡(jiǎn)單封裝,因此放到一個(gè)單獨(dú)的文件里面進(jìn)行引用,可以方便的進(jìn)行復(fù)用,這里DbHelper的后綴名使用ttinclude,這里的后綴名可以隨便起,按照微軟的建議:用于include的文件盡量不要使用.tt做后綴名

  • 在頁(yè)面底部定義一些常用變量,以方便操作 <#+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";} #>

    這里我們把數(shù)據(jù)庫(kù)連接串和數(shù)據(jù)庫(kù)、表名字定義一下,方便修改和使用

  • 最后來(lái)編寫用于實(shí)體類生成的代碼 //------------------------------------------------------------------------------ // <auto-generated> // 此代碼由T4模板自動(dòng)生成 // 生成時(shí)間 <#=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by 懶惰的肥兔 // 對(duì)此文件的更改可能會(huì)導(dǎo)致不正確的行為,并且如果 // 重新生成代碼,這些更改將會(huì)丟失。 // </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模板自動(dòng)生成 // 生成時(shí)間 <#=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by 懶惰的肥兔 // 對(duì)此文件的更改可能會(huì)導(dǎo)致不正確的行為,并且如果 // 重新生成代碼,這些更改將會(huì)丟失。 // </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";} #>

    進(jìn)行保存后會(huì)自動(dòng)生成Customers.cs文件

    //------------------------------------------------------------------------------ // <auto-generated> // 此代碼由T4模板自動(dòng)生成 // 生成時(shí)間 2012-07-18 17:51:26 by 懶惰的肥兔 // 對(duì)此文件的更改可能會(huì)導(dǎo)致不正確的行為,并且如果 // 重新生成代碼,這些更改將會(huì)丟失。 // </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; }} }

    ?

      至此完整演示了怎樣一步步根據(jù)數(shù)據(jù)庫(kù)生成實(shí)體類的操作,是不是很簡(jiǎn)單,如對(duì)語(yǔ)法和操作不理解的地方可以參考T4模版引擎之基礎(chǔ)入門,稍微用心研究下,輕松打造屬于自己的代碼生成器。

  •   本文簡(jiǎn)單介紹了基于單個(gè)模板生成數(shù)據(jù)庫(kù)實(shí)體類的示例,離具體實(shí)用還有一定的距離,畢竟總不能為每個(gè)數(shù)據(jù)表建一個(gè)模板吧,下一篇將揭曉如何通過(guò)單個(gè)T4模板生成多個(gè)文件,以及自動(dòng)生成整個(gè)數(shù)據(jù)庫(kù)的所有實(shí)體類,敬請(qǐng)期待

      下班了,拍拍屁股走人。。。

    源碼:T4ConsoleApplication.rar

    注:此文章屬懶惰的肥兔原創(chuàng),版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文鏈接:http://www.cnblogs.com/lzrabbit/archive/2012/07/18/2597953.html

    若您覺(jué)得這篇文章還不錯(cuò)請(qǐng)點(diǎn)擊下右下角的推薦,有了您的支持才能激發(fā)作者更大的寫作熱情,非常感謝。

    如有問(wèn)題,可以通過(guò)lzrabbit@126.com聯(lián)系我。

    總結(jié)

    以上是生活随笔為你收集整理的[转]T4模版引擎之生成数据库实体类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。

    主站蜘蛛池模板: 国产精品三级av | 美女一区二区三区四区 | 午夜电影福利网 | 在线观看一级片 | 亚洲一区二区视频在线观看 | 在线免费观看黄网站 | 毛片视频网站在线观看 | 国产亚洲一区二区三区四区 | 国产丝袜第一页 | 精品视频不卡 | 713电影免费播放国语 | 日韩精品色哟哟 | 欧美精品一二三区 | 精品人伦一区二区三区 | 亚洲日日日 | 亚州激情视频 | 亚洲国产婷婷 | 久久一热| 激情综合网五月 | 亚洲免费在线观看av | 美女被变态侵犯 | 自拍偷拍欧美激情 | 国产1区在线观看 | 99久久黄色 | 黄色网址在线免费播放 | 亚洲男人天堂2018 | 91伦理在线 | 综合久色| 成人性生活毛片 | 97成人免费视频 | 亚洲五月天综合 | 国产在线二区 | 一卡二卡三卡在线观看 | 国产欧美一区二区三区精品酒店 | 亚洲精品中字 | 草碰在线视频 | 强行侵犯视频在线观看 | 91日韩精品 | 男人的天堂影院 | 色乱码一区二区三区在线男奴 | 亚洲第一在线播放 | 中国一及毛片 | 国产口爆吞精一区二区 | 99色图| 欧美蜜臀 | 日日夜夜操av | 视频久久精品 | 亚洲男人第一网站 | 精品久久久久久无码人妻 | 久久一级视频 | 九九爱国产| 中国亚洲女人69内射少妇 | 国产精品欧美激情在线播放 | 亚洲精品国产精品乱码不卡√香蕉 | 久久久久人妻精品一区二区三区 | 男女黄床上色视频免费的软件 | 久久理论视频 | 亚洲大胆视频 | 免费久久一级欧美特大黄 | 国产一区二区三区视频在线 | 在线视频亚洲色图 | 日韩欧美视频在线播放 | 亚洲一区日本 | 色婷婷综合五月 | 涩涩网站入口 | bbbbbxxxxx性欧美| 男生操女生在线观看 | 国产精品熟女久久久久久 | 麻豆免费在线观看视频 | av草逼| 一区二区国产在线观看 | 91成人小视频 | 亚洲精品在线免费看 | 国产精品18 | 男女在楼梯上高潮做啪啪 | 日韩三级中文字幕 | 欧美一级大黄 | 色爱综合 | 色屁屁影院www国产高清麻豆 | 热99 | 91视频合集 | h视频免费在线观看 | 国产精品人人妻人人爽 | 性色视频在线 | 国产精选第一页 | 中文字幕一区二区人妻痴汉电车 | 福利在线影院 | 成人免费毛片足控 | 久久精品国产亚洲7777 | 日韩毛片视频 | 特级毛片www | 国产一线天粉嫩馒头极品av | 亚洲成人动漫在线观看 | 国产精品88 | 亚洲AV乱码国产精品观看麻豆 | 99热日本 | 肥臀av| 亚洲久久久久久 | 国产精品黄视频 |