NHibernate 功能強大但映射檔 .hbm.xml 繁瑣易錯。Castle ActiveRecord 以**屬性取代 XML 映射**,底層封裝 NHibernate,提供極簡的 O/R Mapping 體驗:定義類別、標註屬性、繼承基類,即可完成資料庫 CRUD,零映射檔、零手寫 SQL。
CREATE TABLE Users (
LogonID int IDENTITY(1,1) PRIMARY KEY,
LogonName varchar(40),
Password varchar(20),
EmailAddress varchar(40),
LastLogon datetime
);
using System;
using Castle.ActiveRecord;
[ActiveRecord("Users")]
public class User : ActiveRecordBase {
private int _id;
private string _name;
private string _password;
private string _emailAddress;
private DateTime _lastLogon;
[PrimaryKey(PrimaryKeyType.Identity, "LogonID")]
public int Id { get { return _id; } set { _id = value; } }
[Property("LogonName")]
public string Name { get { return _name; } set { _name = value; } }
[Property("Password")]
public string Password { get { return _password; } set { _password = value; } }
[Property("EmailAddress")]
public string Email { get { return _emailAddress; } set { _emailAddress = value; } }
[Property("LastLogon")]
public DateTime LastLogon { get { return _lastLogon; } set { _lastLogon = value; } }
// 靜態輔助方法(可選)
public static void DeleteAll() => DeleteAll(typeof(User));
public static IList FindAll() => FindAll(typeof(User));
public static User Find(int id) => (User)FindByPrimaryKey(typeof(User), id);
}
關鍵點:
ActiveRecordBase 獲得 CRUD 方法(Create/Update/Delete/Save/Find/FindAll)。[ActiveRecord("TableName")] 指定對應資料表。[PrimaryKey] 定義主鍵策略與欄位名。[Property("ColumnName")] 映射欄位,屬性名與欄位名同則可省略參數。App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<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.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="hibernate.connection.connection_string" value="Data Source=.;Initial Catalog=ARDemo;Integrated Security=SSPI" />
</config>
</activerecord>
</configuration>
初始化(應用啟動時一次):
var source = (IConfigurationSource)ConfigurationManager.GetSection("activerecord");
ActiveRecordStarter.Initialize(source, typeof(User));
[Test] public void AddUser() {
var user = new User {
Name = "Terrylee",
Password = "aaa",
Email = "lhj_cauc@163.com",
LastLogon = DateTime.Now
};
user.Create(); // INSERT
}
[Test] public void FindAll() {
var list = User.FindAll();
Assert.AreEqual(2, list.Count);
}
[Test] public void FindById() {
var user = User.Find(5);
Assert.AreEqual("Terrylee", user.Name);
}
[Test] public void UpdateUser() {
var user = User.Find(5);
user.Name = "Aero";
user.Update(); // UPDATE
}
[Test] public void DeleteUser() {
var user = new User { Id = 7 };
user.Delete(); // DELETE
}
[Test] public void DeleteAll() {
User.DeleteAll(); // TRUNCATE/DELETE ALL
}
全程無 SQL、無參數綁定、無連接管理,純物件操作。
Castle.ActiveRecord.Generator.exe(安裝目錄 \Bin\net-1.1\)。[ActiveRecord]、[PrimaryKey]、[Property] 等屬性,並可選擇生成 FindAll/Find 靜態方法。注意:生成關聯關係(One-Many/Many-Many)時可能需手動微調 HasMany/BelongsTo/HasAndBelongsToMany 參數。
// Generated by ActiveRecord Generator
namespace ARDemo {
using Castle.ActiveRecord;
[ActiveRecord("Users")]
public class User : ActiveRecordBase {
private int _logonID;
private string _logonName;
private string _password;
private string _emailAddress;
private DateTime _lastLogon;
[PrimaryKey(PrimaryKeyType.Native)]
public int LogonID { get { return _logonID; } set { _logonID = value; } }
[Property] public string LogonName { get { return _logonName; } set { _logonName = value; } }
[Property] public string Password { get { return _password; } set { _password = value; } }
[Property] public string EmailAddress { get { return _emailAddress; } set { _emailAddress = value; } }
[Property] public DateTime LastLogon { get { return _lastLogon; } set { _lastLogon = value; } }
public static void DeleteAll() => ActiveRecordBase.DeleteAll(typeof(User));
public static User[] FindAll() => (User[])ActiveRecordBase.FindAll(typeof(User));
}
}
十分鐘內完成從資料表到可執行 CRUD 實體類別,體驗 ActiveRecord「慣例優於配置」的高效開發模式。下一章將深入配置管理,掌握多資料庫、Web 應用、動態配置等進階場景。