封裝「根據 TableSchema 產生 Insert/Delete/Update/Select 所需參數集合」的邏輯,供 .cst 模板呼叫。
| 方法 | 用途 | 核心邏輯 |
|---|---|---|
| GetInsertParm() | INSERT 參數 | 排除 Identity 欄位、有預設值欄位 |
| GetDeleteParm() | DELETE 參數 | 僅包含 Identity 欄位 (主鍵) |
| GetUpdateParm() | UPDATE 參數 | 排除 Identity 欄位,其餘全部 |
| GetSelectParm() | SELECT 參數 | 僅包含 Identity 欄位 (主鍵查詢) |
| IsIdentity() | 判斷 Identity | 讀取 ExtendedProperties["CS_IsIdentity"] |
| IsDefault() | 判斷有無預設值 | 檢查 ExtendedProperties["CS_Default"] |
| ToSQLType() | 型別映射 | AnsiString → SqlDbType.VarChar,其餘直轉 |
<%@ Property Name="Table" Type="SchemaExplorer.TableSchema" Category="Context" %>
<%@ Property Name="NameSpace" Type="System.String" Default="Company.Product.Module" %>
<%@ Property Name="ClassName" Type="System.String" Default="ClassName" %>
<%@ Property Name="ModelType" Type="System.String" Default="ModelType" %>
<%@ Property Name="ModelName" Type="System.String" Default="ModelName" %>
<%@ Property Name="InsertParm" Type="CodeSmith.CustomProperties.NameValueCollection" %>
<%@ Property Name="DeleteParm" Type="CodeSmith.CustomProperties.NameValueCollection" %>
<%@ Property Name="UpdateParm" Type="CodeSmith.CustomProperties.NameValueCollection" %>
<%@ Property Name="SelectParm" Type="CodeSmith.CustomProperties.NameValueCollection" %>
DalCode dal = new DalCode(Table)GetInsertParm() 等方法填充參數集合屬性private const string SQL_INSERT_TOPIC = "INSERT INTO <%=Table.Name%> (<%=InsertName%>) VALUES(<%=InsertValue%>)";
private const string SQL_DELETE_TOPIC = "DELETE FROM <%=Table.Name%> WHERE <%=DeleteParm[0].Key%> = @<%=DeleteParm[0].Key%>";
private const string SQL_UPDATE_TOPIC = "UPDATE <%=Table.Name%> SET <%=UpdateString%> WHERE <%=DeleteParm[0].Key%> = @<%=DeleteParm[0].Key%>";
private const string SQL_SELECT_TOPIC = "SELECT * FROM <%=Table.Name%> WHERE <%=SelectParm[0].Key%> = @<%=SelectParm[0].Key%>";
SQLHelper.ExecuteNonQuerySQLHelper.GetCachedParameters/CacheParameters),避免重複建立public static class SQLHelper
{
public static string CONN_STRING_NON_DTC = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
public static int ExecuteNonQuery(string connStr, CommandType type, string sql, SqlParameter[] parms) { ... }
private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
public static SqlParameter[] GetCachedParameters(string cacheKey) { ... }
public static void CacheParameters(string cacheKey, SqlParameter[] parms) { ... }
}
| 現狀 (2008 時代) | 現代化替代 (2024+) |
|---|---|
| CodeSmith 模板生成 .cs 檔 | T4 模板 / Source Generators (Roslyn) / EF Core Scaffold-DbContext |
| 手寫 SQL + SqlParameter | Dapper / EF Core / RepoDb - 微型 ORM |
| SQLHelper 快取參數 | Dapper 內建參數快取 / EF Core 編譯查詢快取 |
| 單表 CRUD | Repository Pattern + Unit of Work / CQRS |
| SQL Server 2000 目標 | .NET 6+ / SQL Server 2019+ / Linux 容器化部署 |
CodeSmith 在 2000 年代為 .NET 開發帶來極大生產力提升,其「Schema 驅動生成」思想延續至今日的 Source Generators、EF Core Scaffolding、OpenAPI 生成器等工具。理解早期框架的生成邏輯(欄位篩選、型別映射、SQL 片段組裝、參數快取),有助於評估現代 ORM 的設計取捨與效能特徵。