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

Castle ActiveRecord 實戰(9):開發必備的 6 大實用技巧總彙整

     編輯:關於.NET

技巧一:實體類別反向生成資料表(Code First)

在實體屬性上標註詳細映射資訊,即可自動建表:

[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。

技巧二:執行外部 SQL 腳本建表(安全模式)

ActiveRecordStarter.Initialize(source, typeof(Blog));
ActiveRecordStarter.CreateSchemaFromFile("MySqlScript.sql"); // 表存在不報錯,資料安全

適合生產部署,配合版本控管的遷移腳本使用。

技巧三:優雅處理資料庫 NULL 值——可為 Null 的實值型別

引用 Nullables.dll 與 Nullables.NHibernate.dll,直接使用對應型別:

CLR 型別可為 Null 對應型別
DateTimeNullableDateTime
intNullableInt32
boolNullableBoolean
decimalNullableDecimal
GuidNullableGuid
[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;

自動以整數值存入資料庫,程式碼可讀性大增。

技巧五:整合 log4net 記錄 NHibernate SQL 與診斷資訊

在 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、參數綁定、延遲載入等診斷資訊。

技巧六:生命週期攔截器——BeforeSave/BeforeLoad/BeforeDelete

覆寫基類方法在持久化前後注入邏輯:

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 等進階應用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved