在實體屬性上標註詳細映射資訊,即可自動建表:
[ActiveRecord("Blogs")]
public class Blog : ActiveRecordBase {
[PrimaryKey(PrimaryKeyType.Native, "blog_id")]
public int Id { get; set; }
[Property("blog_name", NotNull = true, Length = 25)]
public string Name { get; set; }
[Property("blog_author", NotNull = true, Length = 50)]
public string Author { get; set; }
}
// 初始化並建表
ActiveRecordStarter.Initialize(source, typeof(Blog), typeof(Post));
ActiveRecordStarter.CreateSchema(); // 注意:會 Drop 現有表!
關鍵預設值:未指定長度的字串預設 NVARCHAR(255)、允許 Null;數值型預設允許 Null。
ActiveRecordStarter.Initialize(source, typeof(Blog));
ActiveRecordStarter.CreateSchemaFromFile("MySqlScript.sql"); // 表存在不報錯,資料安全
適合生產部署,配合版本控管的遷移腳本使用。
引用 Nullables.dll 與 Nullables.NHibernate.dll,直接使用對應型別:
| CLR 型別 | 可為 Null 對應型別 |
|---|---|
DateTime | NullableDateTime |
int | NullableInt32 |
bool | NullableBoolean |
decimal | NullableDecimal |
Guid | NullableGuid |
[Property]
public NullableDateTime CreatedDate { get; set; }
[Property]
public NullableInt32 Count { get; set; }
無需自行封裝 Nullable<T>,ActiveRecord 內建支援完整對應。
public class Post : ActiveRecordBase {
public enum StatusType { Editing = 0, Published = 1, Archived = 2 }
[Property("status_id")]
public StatusType Status { get; set; }
}
// 使用
post.Status = Post.StatusType.Archived;
自動以整數值存入資料庫,程式碼可讀性大增。
在 App.config/Web.config 加入 log4net 區段:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="rollingFile" type="log4net.Appender.RollingFileAppender">
<param name="File" value="log.txt" />
<param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="rollingFile" />
</root>
</log4net>
<nhibernate>
<add key="hibernate.show_sql" value="true" />
</nhibernate>
初始化前啟用:
log4net.Config.XmlConfigurator.Configure();
ActiveRecordStarter.Initialize(source, typeof(Blog));
即可在日誌檔看到完整 SQL、參數綁定、延遲載入等診斷資訊。
覆寫基類方法在持久化前後注入邏輯:
protected override bool BeforeSave(IDictionary state) {
state["Created"] = DateTime.Now; // 自動填入建立時間
return true; // 返回 false 可取消儲存
}
protected override void BeforeLoad(IDictionary state) {
// 載入前處理,如解密敏感欄位
}
protected override void BeforeDelete(IDictionary state) {
// 刪除前檢查,如軟刪除標記
}
適用於審計欄位自動維護、資料加解密、軟刪除等橫切關注點。
本系列從入門到進階,涵蓋配置、映射、關聯、查詢、驗證、延遲載入、Schema 管理等核心主題。後續將提供完整範例專案,並延伸介紹 Castle 核心組件:Windsor IOC、DynamicProxy、Aspect#、Facilities 等進階應用。