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

Castle ActiveRecord 一對一映射:主鍵關聯與 OneToOne 屬性

     編輯:關於.NET

主鍵關聯模式

一對一關係採用「共享主鍵」:NativePlace 的主鍵同時是外鍵指向 Users.ID。兩表主鍵名稱、型別必須一致,且從表主鍵不可為 Identity。

資料庫腳本

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

CREATE TABLE NativePlace (
    ID INT PRIMARY KEY,  -- 非 Identity
    City VARCHAR(50),
    Province VARCHAR(50)
);

實體定義

User(主表端)

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

    [OneToOne(Cascade = CascadeEnum.All)]
    public NativePlace NativePlace { get; set; }
}

NativePlace(從表端)

[ActiveRecord("NativePlace")]
public class NativePlace : ActiveRecordBase
{
    [PrimaryKey(PrimaryKeyType.Foreign)]  // 關鍵:外鍵主鍵
    public int ID { get; set; }

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

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

    [OneToOne]
    public User User { get; set; }
}

PrimaryKeyType.Foreign 告訴 AR 此主鍵值由關聯的父實體指派。

儲存關聯物件

using (var scope = new TransactionScope())
{
    var user = new User { Name = "jailu", Password = "123456789" };
    var place = new NativePlace { Province = "FuJian", City = "LongYan" };

    user.NativePlace = place;
    place.User = user; // 雙向建立關聯

    user.Save(); // 級聯儲存 NativePlace
    scope.VoteCommit();
}

此模式適用於「擁有」關係強烈、子實體生命週期完全依賴父實體的場景。

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