一對一關係採用「共享主鍵」: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)
);
[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; }
}
[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();
}
此模式適用於「擁有」關係強烈、子實體生命週期完全依賴父實體的場景。