我有一個我需要建模的關係是1:0..1。 A類對B類有要求的參考,但B類可以不存在A類。EF代碼第一個1:0..1關係共享主鍵
我的理解(這可能是錯誤的)是這個EF只能創建這種關係,使得A類沒有它自己的主鍵,但與B類使用相同的主鍵.A類是依賴實體,B類是主鍵。
是否可以編輯現有A類(帶有指向特定B類的鏈接)並將其更改爲鏈接到不同的B類?它的主鍵會發生什麼?引用A類的其他實體會發生什麼?
我有一個我需要建模的關係是1:0..1。 A類對B類有要求的參考,但B類可以不存在A類。EF代碼第一個1:0..1關係共享主鍵
我的理解(這可能是錯誤的)是這個EF只能創建這種關係,使得A類沒有它自己的主鍵,但與B類使用相同的主鍵.A類是依賴實體,B類是主鍵。
是否可以編輯現有A類(帶有指向特定B類的鏈接)並將其更改爲鏈接到不同的B類?它的主鍵會發生什麼?引用A類的其他實體會發生什麼?
public partial class PrimaryEntity
{
public PrimaryEntity()
{
ID = Guid.NewGuid();
}
[Key]
public Guid ID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public partial class DependentEntity
{
public DependentEntity()
{
ID = Guid.NewGuid();
}
[Key]
public Guid ID { get; set; }
public string Name { get; set; }
public Guid CurrentPrimaryEntityId { get; set; }
public virtual PrimaryEntity CurrentPrimaryEntity { get; set; }
}
// override this in DataContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DependentEntity>().HasRequired(a => a.CurrentPrimaryEntity).WithMany().HasForeignKey(a => a.CurrentPrimaryEntityId);
base.OnModelCreating(modelBuilder);
}
protected override void Seed(MyDataComtext db)
{
// here is a restriction that FK must be unique
db.Database.ExecuteSqlCommand("ALTER TABLE dbo.[DependentEntity] ADD CONSTRAINT uc_Dependent UNIQUE(CurrentPrimaryEntityId)");
}
var primary = new PrimaryEntity();
db.PrimaryEntity.Add(PrimaryEntity);
var dependent = new DependentEntity();
dependent.CurrentPrimaryEntity = primary;
db.DependentEntity.Add(dependent);
db.SaveChanges();
像這樣
這是「WithMany」,我總是努力想辦法解決問題。這是違反直覺的,因爲沒有多一個。所以,如果我想限制進一步限制它,以便從不多於一個依賴鏈接到同一個主鏈,那麼我想這是關於我的業務邏輯,而不是EF? –
我想這是你需要的。兩個實體都可能擁有自己的PK。主要項目是獨立的,甚至不瞭解依賴項目。 – potehin143
你的意思是你現在有*類* A-B,它現在應該成爲A-C中的類模型?或者兩個*對象* a-b1,它應該成爲a-b2? –
人員類別具有對地址類別的引用。一個人必須有一個地址,但地址可以用於其他類,如公司。所以,當我創建一個人時,我也會用它創建一個地址。地址表中保存主鍵,然後將其分配給該人。如果人「移動」會發生什麼?歷史數據(如交貨)與舊地址相關聯,因此我不想僅編輯該記錄,我需要將舊地址保留在系統中。 –
在這種情況下,我認爲Person-Address應該是多對多的,而交接表有一個指示哪個地址是當前的字段。您不能更改Person的主鍵(我假定其他實體引用它)。 –