首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

CodeSmith 入門教學:從安裝設定到撰寫第一個範本

     編輯:關於ASP.NET

前言

CodeSmith 是強大的程式碼產生工具。本文記錄 v5.1 學習筆記:中文支援設定、範本六大區域、撰寫 ORM 實體範本實戰。

工具設定

  1. 啟用 Unicode:Tools → Options → Studio → Editor → Enable unicode,支援中文顯示與儲存。
  2. 範本標頭加入編碼:<%@ CodeTemplate ... ResponseEncoding="UTF-8" %>,產出檔案支援中文。
  3. 保留 Tab:取消 Convert tab to spaces,維持縮排風格。

範本六大區域

  1. 範本說明區:<%@ CodeTemplate ... Description="..." %>
  2. 屬性設定區:<%@ Property Name="TableName" Type="string" Default="Users" %> 定義輸入參數。
  3. 註冊組件區:<%@ Assembly Name="SchemaExplorer" %> 參考外部 DLL。
  4. 命名空間引用區:<%@ Import Namespace="SchemaExplorer" %>。
  5. 範本主體區:混合靜態文字與 <%= %>、<% %> 程式碼。
  6. 函式區:<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 設定與範本結構,即可將重複程式碼模式封裝為可參數化、可維護的產生器,大幅提升開發效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved