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
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
public static List
_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
#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 Type CommonType { get { return monType(ColumnType); } } ///
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条)