实体框架 - 使用一对一关系中的导航属性分隔主键
EF对我不友好。我需要创建具有单独主键的一对一关系,同时保留导航属性的便利性。但无论我尝试什么,除非我删除导航属性,否则 EF 都会给出错误。
这是问题的完美说明。如您所见,我无法合并主键。而且我不想模拟 1..* 关系,因为关系始终是 1-1。
public class SingleParent
{
public Guid ParentID { get; set; }
public virtual OnlyChild Child { get; set; }
}
public class OnlyChild
{
public Guid ChildID { get; set; }
public virtual SingleParent Parent { get; set; }
}
// Parent and Child cannot share a primary key because a pediatrician only treats children.
public class Pediatrician
{
public Guid PediatricianID { get; set; }
public virtual List<OnlyChild> Patients;
}
我怎样才能获得这样的导航属性 Parent.Child <==>孩子.父母?我更愿意使用数据注释来执行此操作,以便与其余代码保持一致。任何智慧将不胜感激!
EF is not being friendly to me. I need to create a one-to-one relationship that have separate primary keys, while retaining the convenience of navigation properties. But no matter what I try, EF gives me an error unless I remove the navigation property.
Here's a perfect illustration of the problem. As you can see, I can't merge primary keys. And I don't want to simulate a 1..* relationship, because the relationship is always 1-1.
public class SingleParent
{
public Guid ParentID { get; set; }
public virtual OnlyChild Child { get; set; }
}
public class OnlyChild
{
public Guid ChildID { get; set; }
public virtual SingleParent Parent { get; set; }
}
// Parent and Child cannot share a primary key because a pediatrician only treats children.
public class Pediatrician
{
public Guid PediatricianID { get; set; }
public virtual List<OnlyChild> Patients;
}
How can I get the navigation properties such that Parent.Child <==> Child.Parent? I would prefer to do this with Data Annotations to be consistent with the rest code. Any wisdom would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您向两个实体添加外键,它应该可以与 DataAnnotations 和 Fluent API 一起使用。
这里有一些文档,解释了如何创建一对一关系。
If you add a Foreign Key to both entities it should work with both DataAnnotations and with Fluent API.
Here is some documentation that explains how to create a one-to-one relation.