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

Castle ActiveRecord 一對多映射:HasMany 與 BelongsTo 實作

     編輯:關於.NET

關係概覽

User(一)對 Address(多):一位用戶可擁有多個地址。資料庫以 Address.uID 外鍵關聯 Users.ID。

資料庫結構

CREATE TABLE Users (
    ID INT IDENTITY(1,1) PRIMARY KEY,
    LoginName VARCHAR(50) NOT NULL,
    Password VARCHAR(20) NOT NULL
);

CREATE TABLE Address (
    ID INT IDENTITY(1,1) PRIMARY KEY,
    Province VARCHAR(50),
    City VARCHAR(50),
    uID INT FOREIGN KEY REFERENCES Users(ID)
);

實體映射

User(一端)使用 HasMany

[ActiveRecord("Users")]
public class User : ActiveRecordBase
{
    [PrimaryKey(PrimaryKeyType.Identity, "ID")]
    public int Id { get; set; }

    [Property("LoginName")]
    public string Name { get; set; }

    [Property]
    public string Password { get; set; }

    [HasMany(typeof(Address), Table = "Address", ColumnKey = "uID")]
    public IList Addresses { get; set; } = new ArrayList();
}

關鍵屬性:Table 指定關聯表,ColumnKey 指定該表中指向本表的外鍵欄位。

Address(多端)使用 BelongsTo

[ActiveRecord("Address")]
public class Address : ActiveRecordBase
{
    [PrimaryKey(PrimaryKeyType.Native, "ID")]
    public int Id { get; set; }

    [Property]
    public string Province { get; set; }

    [Property]
    public string City { get; set; }

    [BelongsTo("uId")]
    public User User { get; set; }
}

BelongsTo 的參數為外鍵欄位名,對應資料庫 uID。

新增含集合的資料

using (var scope = new TransactionScope())
{
    var user = new User { Name = "jailu", Password = "123456789" };
    user.Save(); // 先存主表取得 ID

    for (int i = 0; i < 5; i++)
    {
        new Address
        {
            Province = "Province" + i,
            City = "City" + i,
            User = user
        }.Save();
    }
    scope.VoteCommit();
}

若設定 Cascade=SaveUpdate,儲存 User 即可自動級聯儲存 Address 集合,無需逐筆 Save()。

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