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

CodeSmith 教學 (3):實戰 - 自動產生 Yii Framework ActiveRecord 類別

     編輯:關於ASP.NET

實戰範例:透過 CodeSmith 連接資料庫,自動為 Yii Framework 產生所有資料表對應的 ActiveRecord PHP 類別。

從模板建立流程

  1. 建立 C# 專案 → 加入 CodeSmith 專案 → 加入 CodeSmith 範本
  2. Schema Explorer 新增資料連線(本例用 Chinook 資料庫)

Schema Explorer 連線

子範本:PhpActiveRecord.cst

<%@ Template Language="C#" TargetLanguage="PHP" Debug="False" %>
<%@ Property Name="TableName" Type="System.String" Description="Table name" %>
<?php
class <%= TableName %> extends CActiveRecord {
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
    public function tableName() {
        return '<%= TableName %>';
    }
}
?>
<script runat="template">
public override string GetFileName() {
    return TableName + ".php";
}
</script>

主範本:YiiDataModel.cst(批次產生所有資料表)

<%@ CodeTemplate Language="C#" TargetLanguage="Text" %>
<%@ Register Name="ActiveRecord" Template="PhpActiveRecord.cst" MergeProperties="false" %>
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<script runat="template">
public string FirstLetterToUpper(string str) {
    if (str != null && str.Length > 1) 
        return char.ToUpper(str[0]) + str.Substring(1);
    return str?.ToUpper();
}
</script>
<% for (int i = 0; i < SourceDatabase.Tables.Count; i++) { %>
    <% string name = FirstLetterToUpper(SourceDatabase.Tables[i].Name); %>
    <% string filename = @"../ActiveRecordDemo/protected/models/" + name + ".php"; %>
    <% ActiveRecord ar = this.Create<ActiveRecord>(); %>
    <% ar.TableName = name; %>
    <% ar.RenderToFile(filename, true); %>
<% } %>

關鍵技術點

  • Register 指令註冊子範本,Create<T>() 實例化
  • RenderToFile() 直接輸出至指定路徑
  • 主範本遍歷 SourceDatabase.Tables 批次產生
  • FirstLetterToUpper 處理類別命名慣例
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved