[英]How do I specify the foreign key in a one-to-one/zero relationship?
I have a parent entity and a child entity. 我有一个父实体和一个子实体。
In the DB the primary key for parent is p_p_id
and the foreign key in the child is the same p_p_id
在DB中,父级的主键是p_p_id
,子级中的外键是相同的p_p_id
There is no foreign key constraint in the database. 数据库中没有外键约束。
The entities have the properties set up in their respective classes pointing at each other. 实体在各自的类中设置属性,指向彼此。
Parent Class 家长班
public virtual ChildProject ThisChildProject { get; set; }
Child Class 儿童班
public virtual ParentProject ThisParentProjection { get; set; }
There are no annotations on these properties nor on the Ids of either class. 这些属性上没有注释,也没有任何类的ID。
In the config, I tried to do the mapping in the child. 在配置中,我试图在孩子中进行映射。
HasRequired(i => i.ThisParentProject).WithOptional(o => o.ThisChildProject );
What happens is EF tries to map using the primary key of the child and the primary key of the parent. EF会尝试使用子键的主键和父键的主键进行映射。
But I want to use a defined FK in the child and the primary key of the parent 但是我想在子节点中使用已定义的FK和父节点的主键
By default EF uses so called Shared Primary Key Association which uses the dependent entity PK as FK to the principal entity. 默认情况下,EF使用所谓的共享主密钥关联 ,其使用从属实体PK作为主体实体的FK。
You can override that behavior by specifying the hidden (shadow) FK name through Map
-> MapKey
fluent configuration: 您可以通过Map
- > MapKey
fluent配置指定隐藏(阴影) FK名称来覆盖该行为:
HasRequired(e => e.ThisParentProject)
.WithOptional(e => e.ThisChildProject)
.Map(m => m.MapKey("p_p_id"));
Update: Please note the hidden (shadow) word. 更新:请注意隐藏(阴影)字。 EF does not support explicit FK property for this type of relationship - there is no HasForeignKey
fluent method and putting ForeignKey
attribute leads to error. EF不支持此类关系的显式FK属性 - 没有HasForeignKey
流畅方法,并且将ForeignKey
属性导致错误。 So if you have something like this in your ChildProject
class: 所以如果你在ChildProject
类中有这样的东西:
[Column("p_p_id")]
public int ThisParentProjectId { get; set; }
I'm afraid the only option is to remove it and work only with navigation properties. 我担心唯一的选择是删除它并仅使用导航属性。
Depending on your property names, you may need to add an ForeignKey attribute, but the standard collection declaration is fine: 根据您的属性名称,您可能需要添加ForeignKey属性,但标准集合声明很好:
http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
And here is One-One as requested by your updated question: 根据您更新的问题,这是One-One:
http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.