CodeSmith 是強大的程式碼產生工具。本文記錄 v5.1 學習筆記:中文支援設定、範本六大區域、撰寫 ORM 實體範本實戰。
Tools → Options → Studio → Editor → Enable unicode,支援中文顯示與儲存。<%@ CodeTemplate ... ResponseEncoding="UTF-8" %>,產出檔案支援中文。Convert tab to spaces,維持縮排風格。<%@ CodeTemplate ... Description="..." %><%@ Property Name="TableName" Type="string" Default="Users" %> 定義輸入參數。<%@ Assembly Name="SchemaExplorer" %> 參考外部 DLL。<%@ Import Namespace="SchemaExplorer" %>。<%= %>、<% %> 程式碼。<script runat="template"> ... </script> 定義輔助方法。<%@ CodeTemplate Language="C#" TargetLanguage="C#" ResponseEncoding="UTF-8" Description="產生實體類別" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.ComponentModel.DataAnnotations;
namespace MyApp.Entities
{
public class <%= SourceTable.Name %>
{
<% foreach (ColumnSchema col in SourceTable.Columns) { %>
[Column("<%= col.Name %>")]
public <%= GetNetType(col) %> <%= col.Name %> { get; set; }
<% } %>
}
}
<script runat="template">
<% string GetNetType(ColumnSchema col) {
// 對應 SQL 型別至 CLR 型別
switch (col.NativeType) { ... }
} %>
</script>
掌握 CodeSmith 設定與範本結構,即可將重複程式碼模式封裝為可參數化、可維護的產生器,大幅提升開發效率。