文字範本(T4) - 透過資料表產生 enum 的內容

  • 391
  • 0
  • C#
  • 2016-10-29

參考範例:
91大 - [.NET]透過 T4 產生對應 DB table 的 entity
https://dotblogs.com.tw/hatelove/archive/2012/07/10/generating-entity-classes-mapping-table-by-using-t4-templates.aspx

我的需求是從資料庫抓出資料來產生 enum 的內容
補充:這個做法還可以再修改為較容易維護的方式。

資料表是 Northwind 的 Categories

.tt 檔的內容如下:

<#@ template language="C#" debug="True" hostspecific="True" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Data" #>

using System;
<#
	using (SqlConnection conn = new SqlConnection())
	{
		string table = "Categories";
		string sql = @"SELECT * FROM @table WHERE CategoryID < @cid";

		conn.ConnectionString = @"Data Source =.\mssql2016; Initial Catalog = Northwind; Integrated Security = True";
		conn.Open();
		sql = sql.Replace("@table", table);
		SqlCommand cmd = new SqlCommand(sql, conn);
		cmd.Parameters.Clear();		
		cmd.Parameters.AddWithValue("@cid", 10);
		SqlDataReader dr = cmd.ExecuteReader();
		DataTable dt = new DataTable();
		dt.Load(dr);
		List<string> strs = new List<string>();
		foreach (DataRow row in dt.Rows)
		{ 
			strs.Add($"{removeSign(row["CategoryName"].ToString())}={row["CategoryID"]}");
		}
#>
public enum <#=table#>
{
	<#= string.Join(",\r\n    ",strs)#>
}
<#
		
	}
#>

<#+
	private static string removeSign(string str)
	{
		str = str.Replace(" ","");
		str = str.Replace("/", "");
		return str;
	}
#>

儲存後,產生的內容如下: