T4模板使用记录,生成Model、Service、Repository
?
自己目前在搭建一個.NET Core的框架,本來是打算使用前端做代碼生成器直接生成到文件的,快做好了。感覺好像使用T4更方便一些,所以也就有了這篇文章~?
我還是有個問題沒解決,就是我想生成每個類(接口)單獨的文件~,如果有老師知道指點下啊~
在網上找了一篇相關文章?本文也是基于這個做了一下自己的修改。
首先公共程序集創建一個DbHelper.ttinclude
主要就是鏈接數據庫,搜索數據庫表及表中字段的信息。
你可以得到這樣的結果:瞬間明了了,然后就? 愛的魔力轉圈圈~ 循環就好了!
代碼是這樣的:
<#+public class config{public static readonly string ConnectionString="Data Source=(local);Integrated Security=true;Initial Catalog=LJDAPP;";public static readonly string DbDatabase="LJDAPP"; }public class DbHelper{ public static List<DbTable> GetDbTables(string connectionString, string database){ string sql = string.Format(@"SELECTobj.name tablename,schem.name schemname,ISNULL(g.value,'') [description],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_idleft join {0}.sys.extended_properties g ON (obj.object_id = g.major_id AND g.minor_id = 0 AND g.name= 'MS_Description')where type='U' order by obj.name", database); DataTable dt = GetDataTable(connectionString, sql);return dt.Rows.Cast<DataRow>().Select(row => new DbTable{TableName = row.Field<string>("tablename"),SchemaName = row.Field<string>("schemname"),Description=row.Field<string>("description"),Rows = row.Field<int>("rows"),HasPrimaryKey = row.Field<bool>("HasPrimaryKey")}).ToList();}public static List<DbColumn> GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo"){ string 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);SqlParameter 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();}public 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;}}}/// <summary>/// 表結構/// </summary>public sealed class DbTable{/// <summary>/// 表名稱/// </summary>public string TableName { get; set; }/// <summary>/// 表的架構/// </summary>public string SchemaName { get; set; }/// <summary>/// 表的說明/// </summary>public string Description { get; set; }/// <summary>/// 表的記錄數/// </summary>public int Rows { get; set; }/// <summary>/// 是否含有主鍵/// </summary>public bool HasPrimaryKey { get; set; }}/// <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; }}public 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;}}#> View Code這個其實也是可以一起放到模板里的,不過因為好幾個地方都需要用到,為了修改方便,還是單獨拿出來比較好。
使用的時候會用到:
<#@ include file="$(ProjectDir)../LJD.App.Util/T4/DbHelper.ttinclude" #>顯而易見,我放到了 LJD.App.Util類庫下T4文件夾
這里說下T4 程序集指令? 還有一篇文章:T4模版引擎之基礎入門?是這樣說的
<#@ assembly name="[assembly strong name|assembly file name]" #>?
1、程序集指令相當于VS里面我們添加程序集引用的功能,該指令只有一個參數name,用以指定程序集名稱,如果程序集已經在GAC里面注冊,那么只需要寫上程序集名稱即可,如<#@?assembly?name="System.Data.dll"?#>,否則需要指定程序集的物理路徑。
2、T4模版的程序集引用是完全獨立的,也就是說我們在項目中引用了一些程序集,然后項目中添加了一個T4模版,T4模版所需要的所有程序集引用必須明確的在模版中使用程序集執行引用才可以。
3、T4模版自動加載以下程序集Microsoft.VisualStudio.TextTemplating.1*.dll、System.dll、WindowsBase.dll,如果用到了其它的程序集需要顯示的使用程序集添加引用才可以
4、可以使用 $(variableName) 語法引用 Visual Studio 或 MSBuild 變量(如 $(SolutionDir)),以及使用 %VariableName% 來引用環境變量。介紹幾個常用的$(variableName) 變量:
$(SolutionDir):當前項目所在解決方案目錄
$(ProjectDir):當前項目所在目錄
$(TargetPath):當前項目編譯輸出文件絕對路徑
$(TargetDir):當前項目編譯輸出目錄,即web項目的Bin目錄,控制臺、類庫項目bin目錄下的debug或release目錄(取決于當前的編譯模式)
舉個例子:比如我們在D盤根目錄建立了一個控制臺項目TestConsole,解決方案目錄為D:\LzrabbitRabbit,項目目錄為
D:\LzrabbitRabbit\TestConsole,那么此時在Debug編譯模式下
$(SolutionDir)的值為D:\LzrabbitRabbit
$(ProjectDir)的值為D:\LzrabbitRabbit\TestConsole
$(TargetPath)值為D:\LzrabbitRabbit\TestConsole\bin\Debug\TestConsole.exe
$(TargetDir)值為D:\LzrabbitRabbit\TestConsole\bin\Debug\
好了,準備工作都做完了,要創建T4模板了,這個還要圖嗎?
然后貼上這段代碼,在foreach中發揮你的想想吧!對了,要注意命名空間和using哈~
<#@ output extension=".cs" #> <#@ assembly name="System.Core" #> <#@ assembly name="System.Data" #> <#@ assembly name="System.Data.DataSetExtensions" #> <#@ assembly name="System.Xml" #> <#@ 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)../LJD.App.Util/T4/DbHelper.ttinclude" #> //------------------------------------------------------------------------------ // <auto-generated> // 此代碼由T4模板自動生成 // 生成時間 <#= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by Jelly // 對此文件的更改可能會導致不正確的行為,并且如果重新生成代碼,這些更改將會丟失。 // </auto-generated> //------------------------------------------------------------------------------ using LJD.App.Model.DbModels;namespace LJD.App.Repository.IRepository {<# foreach(DbTable table in DbHelper.GetDbTables(config.ConnectionString, config.DbDatabase)){#> <# if(table.TableName!="Base") {#>/// <summary>/// <#=table.Description#>/// </summary> public partial interface I<#=table.TableName#>Repository : IBaseRepository<<#=table.TableName#>>{} <#} #><# }#> }?
轉載于:https://www.cnblogs.com/jellydong/p/10838075.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的T4模板使用记录,生成Model、Service、Repository的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件开发冲刺3
- 下一篇: 如何将项目上传到GitHub