Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 612
Smeegs Avatar asked Mar 27 '17 17:03

Smeegs


1 Answers

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:

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. So if you have something like this in your ChildProject class:

[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.

like image 67
Ivan Stoev Avatar answered Oct 05 '22 08:10

Ivan Stoev