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

Castle ActiveRecord 實戰(1):零基礎快速入門——從建表到 CRUD 與代碼生成器完整演練

     編輯:關於.NET

前言:為什麼選擇 ActiveRecord?

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

步驟四:輕鬆 CRUD

[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、無參數綁定、無連接管理,純物件操作。

步驟五:ActiveRecord Generator 視覺化生成實體代碼

  1. 執行 Castle.ActiveRecord.Generator.exe(安裝目錄 \Bin\net-1.1\)。
  2. 選擇 Project Explorer 面板,點擊 Add Database Connection 圖示,設定連接字串並給連接起別名(勾選「允許儲存密碼」避免登入失敗)。
  3. 切換 ActiveRecord Components 面板,將 ActiveRecord 元件拖曳至左側設計面,選擇剛建立的資料庫連接。
  4. 展開資料表,勾選所需欄位,設定類別名、命名空間、主鍵策略等。
  5. 選單 Project → Generate Code,指定輸出路徑、語言(C#/VB.NET)、是否覆蓋既有檔案。
  6. 生成代碼自動包含 [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 應用、動態配置等進階場景。

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