c#利用t4模板,自动生成Model类

c#利用t4模板,自动生成Model类

2023年7月13日发(作者:)

c#利⽤t4模板,⾃动⽣成Model类我们在⽤ORM(⽐如dapper)的时候,很多时候都需要⾃⼰写Model层(当然也有很多orm框架⾃带了这种功能,⽐如ef),特别是表⾥字段⽐较多的时候,⼀个Model要写半天,⽽且Model如果⽤于MVVM中,我们还需要添加PropertyChanged触发代码。发现t4模板可以⾃动⽣成代码,于是就写了⼀个。这个t4模板⽂件⽤了很久了,分享下。<#@ template debug="false" hostspecific="false" language="C#" #><#@ output extension=".cs" #><#@ 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="ude" #>//------------------------------------------------------------------------------// ⽣成时间 <#=ng("yyyy-MM-dd HH:mm:ss")#> by ly//------------------------------------------------------------------------------using System;using c;using ;using ;namespace {

<#

string tables="CK_T_Template,CK_T_MES_MV,CK_T_MES_RPT,CK_T_MES_ROUNTINGS"; string[] ts=(new char[]{','}); for (int i=0;i<;i++) { string tableName=ts[i];

#>

public partial class <#= tableName #>:ModelBase { <# foreach(DbColumn column in olumns(tionString, base, tableName)){#> ///

/// <#=#> ///

private <#= Type#><# if(eType && able){#>?<#}#> _<#=Name#> ; public <#= Type#><# if(eType && able){#>?<#}#> <#=Name#>

{ get { return _<#=Name#> ; } set { _<#=Name#>=value; RaisePropertyChanged("<#=Name#>");

} } <#}#>

} <#

} #>}<#+ public class config { public static readonly string ConnectionString="Data Source=192.168.1.135;Initial Catalog=dbname;User ID=sa;pwd=xxx"; public static readonly string DbDatabase="dbname";

}#>从代码⾥可以看出,我们在每个⽣成的属性⾥,都添加了 RaisePropertyChanged("<#=Name#>"),这样⽣成的Model也可以⾃动触发PropertyChanged事件了。这⼀⾏ string tables="CK_T_Template,CK_T_MES_MV,CK_T_MES_RPT,CK_T_MES_ROUNTINGS"对应于数据库中的表名,你想将哪个表转化成Model,就将表名写这,保存下就会⾃动⽣成⼀个与表名⼀样的类。这个t4模板引⽤了⼀个ttinclude⽂件,这个⽂件主要处理,根据表名从数据库获取表结构,字段类型等。

<#@ template debug="false" hostspecific="false" language="C#" #><#@ 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="" #><#@ output extension=".txt" #><#+ public class DbHelper { #region GetDbTables

public static List GetDbTables(string connectionString, string database) { string tables=""; #region SQL string sql = (@"SELECT tablename, schemname, , CAST ( CASE

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 ().Select(row => new DbTable { TableName = ("tablename"), SchemaName = ("schemname"), Rows = ("rows"), HasPrimaryKey = ("HasPrimaryKey") }).ToList(); } #endregion #region GetDbColumns

public static List GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo") { #region SQL string sql = (@" WITH indexCTE AS ( SELECT

_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 SqlParameter param = new SqlParameter("@tableName", ar, 100) { Value = ("{0}.{1}.{2}", database, schema, tableName) }; DataTable dt = GetDataTable(connectionString, sql, param); return ().Select(row => new DbColumn() { ColumnID = ("ColumnID"), IsPrimaryKey = ("IsPrimaryKey"), ColumnName = ("ColumnName"), ColumnType = ("ColumnType"), IsIdentity = ("IsIdentity"), IsNullable = ("IsNullable"), ByteLength = ("ByteLength"), CharLength = ("CharLength"), Scale = ("Scale"), Remark = row["Remark"].ToString() }).ToList(); } #endregion

#region GetDataTable

public static DataTable GetDataTable(string connectionString, string commandText, params SqlParameter[] parms) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = Command(); dText = commandText; ge(parms); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable dt = new DataTable(); (dt); return dt; } } #endregion } #region DbTable ///

/// 表结构 /// public sealed class DbTable { /// /// 表名称 /// public string TableName { get; set; } /// /// 表的架构 /// public string SchemaName { get; set; } /// /// 表的记录数 /// public int Rows { get; set; } /// /// 是否含有主键 /// public bool HasPrimaryKey { get; set; } } #endregion #region DbColumn /// /// 表字段结构 /// public sealed class DbColumn { /// /// 字段ID /// public int ColumnID { get; set; } /// /// 是否主键 /// public bool IsPrimaryKey { get; set; } /// /// 字段名称 /// public string ColumnName { get; set; } /// /// 字段类型 /// public string ColumnType { get; set; } /// /// 数据库类型对应的C#类型 /// public string CSharpType { get { return arpType(ColumnType); } } public string DbType { get { return ype(ColumnType); } } /// ///

///

public Type CommonType { get { return monType(ColumnType); } } /// /// 字节长度 /// public int ByteLength { get; set; } /// /// 字符长度 /// public int CharLength { 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 string MapDBType(string dbtype) { if (OrEmpty(dbtype)) return dbtype; dbtype = r(); string csharpType = "object"; switch (dbtype) { case "bigint": csharpType = "64"; break; case "binary": csharpType = ""; break; case "bit": csharpType = "n"; break; case "char": csharpType = ""; break; case "date": csharpType = "me"; break; case "datetime": csharpType = "me"; break; case "datetime2": csharpType = "me2"; break; case "datetimeoffset": csharpType = "meOffset"; break; case "decimal": csharpType = "l"; break; case "float": csharpType = ""; break; case "image": csharpType = ""; break; case "int": csharpType = "32"; break; case "money": csharpType = "cy"; break; case "nchar": csharpType = "FixedLength"; break; case "ntext": csharpType = ""; break; case "numeric": csharpType = "l"; break; case "nvarchar": csharpType = ""; break; case "real": csharpType = ""; break; case "smalldatetime": csharpType = "me"; break; case "smallint": csharpType = "16"; break; case "smallmoney": csharpType = "l"; break; case "sql_variant": csharpType = ""; break; case "sysname": csharpType = ""; break; case "text": csharpType = ""; break; case "time": csharpType = "me"; break; case "timestamp": csharpType = ""; break; case "tinyint": csharpType = ""; break; case "uniqueidentifier": csharpType = ""; break; case "varbinary": csharpType = ""; break; case "varchar": csharpType = "ring"; break; case "xml": csharpType = ""; break; default: csharpType = ""; 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

#>View Code

t4⽂件保存后,会⾃动⽣成类⽂件 这样,我们省去了很多代码量。

发布者:admin,转转请注明出处:http://www.yc00.com/news/1689246092a225602.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信