<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Data" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
// 导入MultipleOutputHelper.ttinclude文件
<#@include file="$(SolutionDir)\HClubMall.Model\T4\MultipleOutputHelper.ttinclude" #> <#
var manager = Manager.Create(Host, GenerationEnvironment);
manager.StartHeader();
#> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace HClubMall.Model
{
<# manager.EndBlock(); #> <#
string connectionString= "server=192.168.0.23;database=Hclub1031;uid=sa;pwd=seindotnet;";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open(); string selectQuery ="SET FMTONLY ON; select * from @tableName; SET FMTONLY OFF;";
SqlCommand command = new SqlCommand(selectQuery,conn);
SqlDataAdapter ad = new SqlDataAdapter(command);
System.Data.DataSet ds = new DataSet();
System.Data.DataTable schema = conn.GetSchema("Tables"); foreach(System.Data.DataRow row in schema.Rows)
{
ds.Tables.Clear();
string tb_name = row["TABLE_NAME"].ToString();
command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString());
ad.FillSchema(ds,SchemaType.Mapped,tb_name);
manager.StartNewFile(tb_name+".cs");
#>
[Serializable]
/// <summary>
/// 实体-<#=tb_name#>
/// </summary>
public partial class <#=tb_name#>
{
<#
PushIndent(" ");
WriteLine(" #region 属性");
foreach (DataColumn dc in ds.Tables[].Columns)
{
WriteLine("/// <summary>");
WriteLine("/// ");
WriteLine("/// </summary>");
WriteLine("public " + dc.DataType.Name + (dc.AllowDBNull && (dc.DataType.Name.ToLower() != "string")&&(dc.DataType.Name.ToLower()!="byte[]") ? "? ": " ") + dc.ColumnName + " { get; set; }");
}
WriteLine("#endregion");
PopIndent();
#>
}
<#
manager.EndBlock();
}
conn.Close();
#> <# manager.StartFooter(); #>
}
<# manager.EndBlock(); #> <# manager.Process(true); #>
1.需要引用一个国外的批量生成代码模板MultipleOutputHelper.ttinclude
2.创建一个T4模板,复制上面的代码放到新创建的T4模板中。
3.Ctrl+S
4.效果图:
注意:
MultipleOutputHelper.ttinclude项目在桌面时会报错。