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
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.
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.
But I want to use a defined FK in the child and the primary key of the parent
By default EF uses so called Shared Primary Key Association which uses the dependent entity PK as FK to the principal entity.
You can override that behavior by specifying the hidden (shadow) FK name through
Map
->MapKey
fluent configuration: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 puttingForeignKey
attribute leads to error. So if you have something like this in yourChildProject
class: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:
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:
http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx