无法通过映射来做到这一点,因为 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
}