由於EF關係嚴格遵循DB關係,因此無法通過映射來完成此操作。此外,EF中的一對一關係基於將外鍵放在依賴表中的主鍵上(地址和人員需要具有完全相同的主鍵值),並且此要求不會與期望中的舊地址一起工作表格也是如此。
我想嘗試這種方法(未測試):
public class MyContext : DbContext {
public MyContext() {
((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
(sender, e) => {
var person = e.Person as Person;
if (person != null) {
// Fill the property manually
person.Address = this.Addresses.FirstOrDefault(/* some condition */);
}
}
protected override void OnModelCreating(DbModelBuilder builder) {
// Do not map the propery
builder.Entity<Person>().Ignore(p => p.Address);
// other mapping
}
public override int SaveChanges() {
// TODO: here you must have your own change tracking logic
// for address to know when the address has changed and
// new record must be created in the database for old address
return base.SaveChanges();
}
// rest of context class
}
豈不是最自然不過的事情是以前的地址存儲在一個單獨的表,例如AddressHistory?他們在同一張桌子上真的很重要嗎? –
這是一個複雜的表格,我不希望重複結構(和伴隨邏輯)。我不相信我的桌子設計應該由工具來驅動,所以我寧願像我直接創建桌子一樣構造桌子。 (我希望我先用DB)。 –