2023年7月13日发(作者:)
C#T4模板在项⽬中的使⽤1.什么是t4模版T4,即4个T开头的英⽂字母组合:Text Template Transformation Toolkit。T4()是微软官⽅在VisualStudio 2008中开始使⽤的代码⽣成引擎。在 Visual Studio 中,“T4 ⽂本模板”是由⼀些⽂本块和控制逻辑组成的混合模板,它可以⽣成⽂本⽂件。 在 Visual C# 或 Visual Basic 中,控制逻辑编写为程序代码的⽚段。⽣成的⽂件可以是任何类型的⽂本,例如⽹页、资源⽂件或任何语⾔的程序源代码。现在的VS中只要与代码⽣成相关的场景基本上都能找T4的⾝影,⽐如MVC的视图模板,Entity Framwork的DataContext模板等等。可以所T4模版课快速帮你⽣产实体类或者需要重复编写但是格式⼀致的代码2.T4模版初试篇⾸先看下运⾏效果: 我这⼿⾥有⼀个还没有编写实体类的项⽬,我们拿则个项⽬来测试下t4模版的强⼤之处(1)⾸先我先新创建⼀个类库专门存放t4模版 (2)新创建⼀个 ude 模板,主要是数据库操作类<#+ public class config { public static readonly string ConnectionString = "Server=.;Database=XXXX;User ID=sa;Password=你的数据库密码"; public static readonly string DbDatabase = ""; public static readonly string TableName = ""; }#><#+
public class DbHelper { #region GetDbTables public static List
if (!OrEmpty(tables)) { tables = (" and in ('{0}')", e(",", "','")); } string sql = (@"SELECT tablename from {0}.s obj
inner join {0}.exes idx on _id= and <=1 INNER JOIN {0}.s schem ON _id=_id left join {0}.ed_properties g ON (_id = _id AND _id = 0 AND = 'MS_Description') where type='U' {1}
order by ", database,tables); order by ", database,tables); DataTable dt = GetDataTable(connectionString, sql); return
WHEN (SELECT COUNT(1) FROM s WHERE object_id= _ID AND is_primary_key=1) >=1 THEN 1 ELSE 0 END
AS BIT) HasPrimaryKey
from {0}.s obj
inner join {0}.exes idx on _id= and <=1 INNER JOIN {0}.s schem ON _id=_id where type='U' {1} order by ", database, tables); #endregion DataTable dt = GetDataTable(connectionString, sql); return
_id, _column_id, _id
FROM {0}.s idx INNER JOIN {0}._columns ic ON _id = _id AND _id = _id WHERE _id =OBJECT_ID(@tableName) AND _primary_key=1 ) select _id ColumnID, CAST(CASE WHEN _id IS NULL THEN 0 ELSE 1 END AS BIT) IsPrimaryKey, ColumnName, ColumnType, _identity IsIdentity, _nullable IsNullable, cast(_length as int) ByteLength, ( ( case
when ='nvarchar' and _length>0 then _length/2
when ='nchar' and _length>0 then _length/2 when ='ntext' and _length>0 then _length/2
else _length end ) CharLength, cast(ion as int) Precision, cast( as int) Scale, Remark from {0}.s colm inner join {0}. systype on _type_id=_type_id and _type_id=_type_id left join {0}.ed_properties prop on _id=_id and _id=_id LEFT JOIN indexCTE ON _id=_id AND _id=_id
where _id=OBJECT_ID(@tableName) order by _id", database); #endregion DataTable dt = GetDataTable(connectionString, sql, param); return
public sealed class DbColumn {
public int ColumnID { get; set; }
public bool IsPrimaryKey { get; set; }
public string ColumnName { get; set; }
public string ColumnType { get; set; }
public string CSharpType { get { return arpType(ColumnType); } } ///
/// public Type CommonType { get { return monType(ColumnType); } } public int ByteLength { get; set; } public int CharLength { get; set; } public int Precision{get;set;} public int Scale { get; set; } public bool IsIdentity { get; set; } public bool IsNullable { get; set; } public string Remark { get; set; } } #endregion #region SqlServerDbTypeMap public class SqlServerDbTypeMap { public static string MapCsharpType(string dbtype) { if (OrEmpty(dbtype)) return dbtype; dbtype = r(); 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 (OrEmpty(dbtype)) return e(); dbtype = r(); 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 #>(3)再创建⼀个 ude 实体类⽣产模版<#@ assembly name=""#><#@ assembly name="EnvDTE"#><#@ import namespace="c"#><#@ import namespace=""#><#@ import namespace=""#><#@ import namespace="mplating"#><#+class Manager{ public struct Block { public int Start, Length; public String Name,OutputPath; } public List
public void EndBlock() { = - ; (currentBlock); } public void Process(bool split) { String header = ng(, ); String footer = ng(, ); e(); foreach(Block block in blocks) { String fileName = e(Path, ); if (split) { String content = header + ng(, ) + footer; File(fileName, content); (, ); } else { File(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) { llText(fileName, content); } internal virtual void DeleteFile(String fileName) { if ((fileName)) (fileName); }}class VSManagementStrategy : ManagementStrategy{ private tItem templateProjectItem; internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) { IServiceProvider hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) if (hostServiceProvider == null) throw new ArgumentNullException("Could not obtain hostServiceProvider"); dte = ()vice(typeof()); if (dte == null) throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = ojectItem(teFile); } internal override void CreateFile(String fileName, String content) { File(fileName, content); //((EventHandler)delegate { mFile(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(tItem projectItem in tItems) { if (_FileNames(0) == fileName) { (); return; } } }}#> (3)创建实体类运⾏时⽂本模版 <#@ template debug="false" hostspecific="true" language="C#" #><#@ output extension="/" #><#@ assembly name="" #><#@ assembly name="" #><#@ assembly name="" #><#@ assembly name="" #><#@ import namespace="System" #><#@ import namespace="" #><#@ import namespace="" #><#@ import namespace="" #><#@ import namespace="ent" #><#@ import namespace="c" #><#@ import namespace="" #><#@ include file="$(ProjectDir)ude" #><#@ include file="$(ProjectDir)ude" #><# var manager = new Manager(Host, GenerationEnvironment, true); #><#
var OutputPath1 =ectoryName(ectoryName(ectoryName(teFile+"..")+"..")+".."); OutputPath1=e(OutputPath1,"rk","Models_New"); if (!(OutputPath1)) { Directory(OutputPath1); }#><# foreach (var item in ablesNew(tionString, base,ame)) { var tableName=ng(); lock(tableName+".cs",OutputPath1);//⽂件名 #>using System;using notations;using ;namespace { ///
public class <#=tableName#> { <# foreach(DbColumn column in olumns(tionString, base, tableName)){#> ///
if(aryKey)
{#>[Key] <#}#><# if(!able) {#>[Required] <# }#>public <#= Type#><# if(eType && able){#>?<#}#> <#=Name#> { get; set; } <# } #>
}}
<# ck();
} s(true); #>我们这⾥是在同个项⽬中的Models_New⽂件夹⽣产实体类 最后只需右键运⾏⾃定义⼯具就可以快速⽣成实体类了,运⾏代码上⾯的gif图所⽰当然t4模版不仅仅只能⽣成实体类还能⽣产其他固定代码,其他的我们下⼀次来讲解
发布者:admin,转转请注明出处:http://www.yc00.com/web/1689246506a225621.html
评论列表(0条)