在entity项目里新建模板DBEntity.tt
<#@ template debug="false" hostspecific="true" language="C#" #><#@ include file="$(SolutionDir)/Packages/T4.TemplateFileManager.2.1.2/tools/ttinc/TemplateFilemanager.CS.ttinclude" #><#@ include file="$(SolutionDir)/Packages/T4.TemplateFileManager.2.1.2/tools/ttinc/DbHelper.CS.ttinclude" #><#@ output extension=".txt" #><# // Recommended editor: Tangible T4 Editor (http://t4-editor.tangible-engineering.com/Download_T4Editor_Plus_ModelingTools.html)// after save SimpleSample.tt, the output will be generated in the TestFolder of the PRojectvar fileProperties = new FileProperties(){ BuildAction = BuildAction.Compile};var fileManager = TemplateFileManager.Create(this);fileManager.IsAutoIndentEnabled = true;fileManager.CanOverwriteExistingFile = true;fileManager.StartHeader();#>//<summary file="$filename$" company="ldy">//------------------------------------------------------------------------------// <auto-generated>// 此代码是根据模板生成的。//// 手动更改此文件可能会导致应用程序中发生异常行为。// 如果重新生成代码,则将覆盖对此文件的手动更改。//出自 http://www.VEVb.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!// </auto-generated>//------------------------------------------------------------------------------// </summary><# fileManager.EndBlock();var paramTmpl = ParamTextTemplate.Create(this.Host);var session = ParamTextTemplate.GetSessionObject(); var DbTables = DbHelper.GetDbTables(config.ConnectionString, config.DbDatabase); foreach(var table in DbTables){ fileManager.StartNewFile(table.TableName + ".cs", config.NameSpace,"",fileProperties); session["ConnectionString"] = config.ConnectionString; session["DbDatabase"] = config.DbDatabase; session["NameSpace"] = config.NameSpace; session["TableName"] = table.TableName; string output = paramTmpl.TransformText("EntityContent.tt", session); this.Write(output); }fileManager.Process();#><#+ public class config{ public static readonly string ConnectionString="Data Source=192.168.1.10;Initial Catalog=TongJi;User ID=sa;PassWord=123456"; public static readonly string DbDatabase="TongJi"; public static readonly string TableName="TAd"; public static readonly string NameSpace="__System.Entity";}#>
再新建EntityContent.tt
<#@ template debug="false" hostspecific="false" language="C#" #><#@ 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" #><#@ parameter name="ConnectionString" type="System.String" #><#@ parameter name="DbDatabase" type="System.String" #><#@ parameter name="TableName" type="System.String" #><#@ parameter name="NameSpace" type="System.String" #><#@ include file="$(SolutionDir)/Packages/T4.TemplateFileManager.2.1.2/tools/ttinc/DbHelper.CS.ttinclude" #><#@ output extension=".txt" #><#if(ConnectionString!=null&&DbDatabase!=null&&TableName!=null&&NameSpace!=null){#>using System;using System.Collections.Generic;namespace <#=NameSpace#>{ public class <#=TableName#> : BaseEntity { <#foreach(DbColumn column in DbHelper.GetDbColumns(ConnectionString, DbDatabase, TableName)){#> /// <summary> /// <#=GetRemark(column.Remark)#> /// </summary> public <#=column.CSharpType#><#if(column.CommonType.IsValueType && column.IsNullable){#>?<#}#> <#=column.ColumnName#> { get; set; } <#}#> }}<#}#><#+public string GetRemark(string str){ char[] strArr =str.ToCharArray(); string newStr = ""; foreach (char cr in strArr) { if (cr == (char)10) { newStr = newStr+cr.ToString()+"///"; } else{ newStr += cr.ToString(); } } return newStr;}#>
注意到有一段
<#@ include file="$(SolutionDir)/Packages/T4.TemplateFileManager.2.1.2/tools/ttinc/TemplateFilemanager.CS.ttinclude" #><#@ include file="$(SolutionDir)/Packages/T4.TemplateFileManager.2.1.2/tools/ttinc/DbHelper.CS.ttinclude" #>在解决方案文件夹目录下的Packages(没有就新建)里新建T4.TemplateFileManager.2.1.2/tools/ttinc/这个目录
新建文件TemplateFilemanager.CS.ttinclude
<#@ assembly name="System.Data.DataSetExtensions.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" #><#+ public class DbHelper { #region GetDbTables public 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 SQL string sql = string.Format(@"SELECT obj.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 1 ELSE 0 END AS BIT) HasprimaryKey from {0}.sys.objects obj inner join {0}.dbo.sysindexes idx on obj.object_id=idx.id and idx.indid<=1 INNER JOIN {0}.sys.schemas schem ON obj.schema_id=schem.schema_id where type='U' {1} order by obj.name", database, tables); #endregion DataTable 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 GetDbColumns public static List<DbColumn> GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo") { #region SQL string sql = string.Format(@" WITH indexCTE AS ( SELECT ic.column_id, ic.index_column_id, ic.object_id FROM {0}.sys.indexes idx INNER JOIN {0}.sys.index_columns ic ON idx.index_id = ic.index_id AND idx.object_id = ic.object_id WHERE idx.object_id =OBJECT_ID(@tableName) AND idx.is_primary_key=1 ) select colm.column_id ColumnID, CAST(CASE WHEN indexCTE.column_id IS NULL THEN 0 ELSE 1 END AS BIT) IsPrimaryKey, co
新闻热点
疑难解答