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

Castle ActiveRecord 入門:屬性化 ORM 映射與基本 CRUD 實作

     編輯:關於.NET

ActiveRecord 簡介

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);
}

第三步:ASP.NET WebForm 呼叫測試

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}";
    }
}

關鍵優勢

  1. 零 XML 映射:屬性即文檔,重構時編譯器即時檢查。
  2. 繼承即功能:無需撰寫 DAO 模板代碼,ActiveRecordBase 已封裝常用操作。
  3. NHibernate 底層:支援延遲載入、快取、複雜查詢等企業級特性。

下一步:組態初始化與自動建表

實體定義完成後,仍需在 Global.asax 的 Application_Start 初始化組態並呼叫 ActiveRecordStarter.CreateSchema() 自動建立資料表,詳細請參考下一篇《Castle.ActiveRecord 組態指南》。

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