Castle ActiveRecord 是建構於 NHibernate 之上的輕量級 ORM 框架,採用 **屬性標註** 取代傳統 XML 映射檔,讓實體類別即映射定義,極大降低資料存取層開發複雜度。
[ActiveRecord("Users")]
public class Users : ActiveRecordBase
{
private int _oid;
[PrimaryKey(PrimaryKeyType.Identity, "Oid")]
public int Oid { get => _oid; set => _oid = value; }
private string _name;
[Property("Name", Length = 100, NotNull = true)]
public string Name { get => _name; set => _name = value; }
private string _sex;
[Property("Sex")]
public string Sex { get => _sex; set => _sex = value; }
private string _age;
[Property("Age")]
public string Age { get => _age; set => _age = value; }
}
[ActiveRecord("Users")]:對應資料表名稱。[PrimaryKey(PrimaryKeyType.Identity, "Oid")]:主鍵自增。[Property]:欄位映射,可指定長度、非空等約束。ActiveRecordBase<T> 即獲得 Create()、Update()、Delete()、Find()、FindAll() 等內建方法。public class UserComponent : ActiveRecordBase
{
public static void Create(Users user) => user.Create();
public static IList QueryAll() => (IList)FindAll(typeof(Users));
public static Users QueryByOid(int oid) => (Users)Find(oid);
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) GridViewDataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
var user = new Users
{
Name = TextBox1.Text.Trim(),
Sex = TextBox2.Text.Trim(),
Age = TextBox3.Text.Trim()
};
UserComponent.Create(user);
GridViewDataBind();
}
public void GridViewDataBind()
{
GridView1.DataSource = UserComponent.QueryAll();
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
var user = UserComponent.QueryByOid(int.Parse(TextBox4.Text.Trim()));
Label1.Text = $"編號:{user.Oid}, 姓名:{user.Name}, 性別:{user.Sex}, 年齡:{user.Age}";
}
}
ActiveRecordBase 已封裝常用操作。實體定義完成後,仍需在 Global.asax 的 Application_Start 初始化組態並呼叫 ActiveRecordStarter.CreateSchema() 自動建立資料表,詳細請參考下一篇《Castle.ActiveRecord 組態指南》。