Entity Framework - bidirectional one-to-one relationship on a foreign key

百般思念 提交于 2019-12-24 04:44:07

问题


I have two entities like Hat and Owner:

+========+          +=========+
|Owner   |----------|Hat      |
+--------| 0/1    1 +---------|
|ID      |          |ID       |
|Name    |          |Size     |
+--------|          +---------|
|HatId   |          |OwnerId  |
+========+          +=========+

(Every Owner has his Hat. Some Hats does not have their owners.)

I've created models:

public class Owner
{
    [Key]
    public Int32 ID { get; set; }
    public String Name { get; set; }
    public virtual Hat Hat { get; set; }
}

public class Hat
{
    [Key]
    public Int32 ID { get; set; }
    public Int32 Size { get; set; }
    public virtual Owner Owner { get; set; }
}

At this point I figured out that:

  • I can create one-to-one relationship on primary key - which I don't want because Hat can change his owner but ID of Hat and ID of Owner should never change after creation.
  • I can create one-to-many relationship - but here I'm unable to create foreign key on "many" side, which will be auto updated.

So question in: Is it possible to create bidirectional one-to-one relationship on a foreign key in Entity Framework?

来源:https://stackoverflow.com/questions/20270588/entity-framework-bidirectional-one-to-one-relationship-on-a-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!