castleproject-1.0-rc2.msi 安裝(或 NuGet 安裝 Castle.ActiveRecord)。Castle.ActiveRecord.dll、NHibernate.dll、Castle.Core.dll。<configSections>
<section name="activerecord"
type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
</configSections>
<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 連線字串。<%@ 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();
}
ActiveRecordStarter.Initialize 必須在應用程式啟動時呼叫**一次**,建立 NHibernate ISessionFactory。CreateSchema() 會依實體屬性自動發出 DDL 建表,**僅適用於開發環境**;生產環境請使用資料庫遷移工具。Initial Catalog 資料庫必須預先存在,僅建立表格。若需支援 MySQL、PostgreSQL、Oracle,只需更換 driver_class、dialect 與連線字串,實體類別完全不用動。
| 錯誤現象 | 可能原因 | 解決方式 |
|---|---|---|
| 找不到組態區段 | configSections 名稱拼錯或組件未引用 | 檢查 section name="activerecord" 與組件引用 |
| 無法連線資料庫 | 連線字串錯誤、防火牆、SQL Server 未啟用 TCP/IP | 用 SSMS 測試連線、檢查 SQL Server 組態管理員 |
| CreateSchema 失敗 | 資料庫不存在、權限不足、方言不匹配 | 確認資料庫存在、授權 db_owner、對應正確 dialect |