Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...