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

Castle ActiveRecord 組態完整指南:Web.config 設定與自動建表初始化

     編輯:關於.NET

安裝與組件引用

  1. 下載 castleproject-1.0-rc2.msi 安裝(或 NuGet 安裝 Castle.ActiveRecord)。
  2. 專案引用:Castle.ActiveRecord.dll、NHibernate.dll、Castle.Core.dll。

Web.config 組態區段註冊

<configSections>
  <section name="activerecord"
           type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
</configSections>

ActiveRecord 具體組態

<activerecord>
  <config>
    <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
    <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
    
    <add key="hibernate.connection.connection_string"
         value="Data Source=.;Initial Catalog=test;Integrated Security=SSPI" />
  </config>
</activerecord>
  • driver_class:資料庫驅動(SQL Server 用 SqlClientDriver)。
  • dialect:SQL 方言(MS SQL 2000/2005/2008 通用)。
  • connection_string:標準 ADO.NET 連線字串。

Global.asax 應用程式啟動初始化

<%@ Application Language="C#" %>
<%@ Import Namespace="Castle.ActiveRecord.Framework" %>
<%@ Import Namespace="Castle.ActiveRecord" %>

void Application_Start(object sender, EventArgs e)
{
    // 1. 取得組態來源
    IConfigurationSource source = ConfigurationManager.GetSection("activerecord") as IConfigurationSource;

    // 2. 初始化 ActiveRecord 框架,掃描實體類別
    // 單一類別
    ActiveRecordStarter.Initialize(source, typeof(ZDS.Test.Model.Users));

    // 或掃描整個組件(需引用 System.Reflection)
    // ActiveRecordStarter.Initialize(Assembly.Load("ZDS.DaiTao.Test.Model"), source);

    // 3. 自動建立資料表(僅開發/測試環境建議開啟)
    ActiveRecordStarter.CreateSchema();
}

關鍵說明

  1. ActiveRecordStarter.Initialize 必須在應用程式啟動時呼叫**一次**,建立 NHibernate ISessionFactory。
  2. CreateSchema() 會依實體屬性自動發出 DDL 建表,**僅適用於開發環境**;生產環境請使用資料庫遷移工具。
  3. 連線字串中的 Initial Catalog 資料庫必須預先存在,僅建立表格。

多資料庫支援

若需支援 MySQL、PostgreSQL、Oracle,只需更換 driver_class、dialect 與連線字串,實體類別完全不用動。

常見錯誤排查

錯誤現象可能原因解決方式
找不到組態區段configSections 名稱拼錯或組件未引用檢查 section name="activerecord" 與組件引用
無法連線資料庫連線字串錯誤、防火牆、SQL Server 未啟用 TCP/IP用 SSMS 測試連線、檢查 SQL Server 組態管理員
CreateSchema 失敗資料庫不存在、權限不足、方言不匹配確認資料庫存在、授權 db_owner、對應正確 dialect
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved