由于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)。 –