T4模板批量生成代码文件
1 <#@ template debug="false" hostspecific="true" language="C#" #> 2 <#@ assembly name="System.Data" #> 3 <#@ assembly name="System.xml" #> 4 <#@ import namespace="System.Collections.Generic" #> 5 <#@ import namespace="System.Data.SqlClient" #> 6 <#@ import namespace="System.Data" #> 7 <#@ assembly name="System.Core" #> 8 <#@ import namespace="System.Linq" #> 9 // 导入MultipleOutputHelper.ttinclude文件 10 <#@include file="$(SolutionDir)\HClubMall.Model\T4\MultipleOutputHelper.ttinclude" #> 11 12 <# 13 var manager = Manager.Create(Host, GenerationEnvironment); 14 manager.StartHeader(); 15 #> 16 17 18 using System; 19 using System.Collections.Generic; 20 using System.Linq; 21 using System.Text; 22 23 namespace HClubMall.Model 24 { 25 <# manager.EndBlock(); #> 26 27 <# 28 string connectionString= "server=192.168.0.23;database=Hclub1031;uid=sa;pwd=seindotnet;"; 29 SqlConnection conn = new SqlConnection(connectionString); 30 conn.Open(); 31 32 string selectQuery ="SET FMTONLY ON; select * from @tableName; SET FMTONLY OFF;"; 33 SqlCommand command = new SqlCommand(selectQuery,conn); 34 SqlDataAdapter ad = new SqlDataAdapter(command); 35 System.Data.DataSet ds = new DataSet(); 36 System.Data.DataTable schema = conn.GetSchema("Tables"); 37 38 foreach(System.Data.DataRow row in schema.Rows) 39 { 40 ds.Tables.Clear(); 41 string tb_name = row["TABLE_NAME"].ToString(); 42 command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString()); 43 ad.FillSchema(ds,SchemaType.Mapped,tb_name); 44 manager.StartNewFile(tb_name+".cs"); 45 #> 46 [Serializable] 47 /// <summary> 48 /// 实体-<#=tb_name#> 49 /// </summary> 50 public partial class <#=tb_name#> 51 { 52 <# 53 PushIndent(" "); 54 WriteLine(" #region 属性"); 55 foreach (DataColumn dc in ds.Tables[0].Columns) 56 { 57 WriteLine("/// <summary>"); 58 WriteLine("/// "); 59 WriteLine("/// </summary>"); 60 WriteLine("public " + dc.DataType.Name + (dc.AllowDBNull && (dc.DataType.Name.ToLower() != "string")&&(dc.DataType.Name.ToLower()!="byte[]") ? "? ": " ") + dc.ColumnName + " { get; set; }"); 61 } 62 WriteLine("#endregion"); 63 PopIndent(); 64 #> 65 } 66 <# 67 manager.EndBlock(); 68 } 69 conn.Close(); 70 #> 71 72 <# manager.StartFooter(); #> 73 } 74 <# manager.EndBlock(); #> 75 76 <# manager.Process(true); #>
1.需要引用一个国外的批量生成代码模板MultipleOutputHelper.ttinclude
2.创建一个T4模板,复制上面的代码放到新创建的T4模板中。
3.Ctrl+S
4.效果图:
注意:
MultipleOutputHelper.ttinclude项目在桌面时会报错。
作者:江宁织造
博客:http://www.cnblogs.com/wgx0428/
博客:http://www.cnblogs.com/wgx0428/