如何以一对一/零关系指定外键? [英] How do I specify the foreign key in a one-to-one/zero relationship?

查看:91
本文介绍了如何以一对一/零关系指定外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父实体和一个子实体。

I have a parent entity and a child entity.

在数据库中,父级的主键为 p_p_id
和子代中的外键是相同的 p_p_id

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.

父类

public virtual ChildProject ThisChildProject { get; set; }

儿童班

public virtual ParentProject ThisParentProjection { get; set; }

这些属性或两个类的ID上都没有注释。

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 );

会发生什么情况,EF尝试使用子级的主键和父级的主键进行映射

What happens is EF tries to map using the primary key of the child and the primary key of the parent.

但是我想在子级和父级的主键中使用已定义的FK

But I want to use a defined FK in the child and the primary key of the parent

推荐答案

默认情况下,EF使用所谓的共享主键关联,它使用从属实体PK作为主体实体的FK。

By default EF uses so called Shared Primary Key Association which uses the dependent entity PK as FK to the principal entity.

您可以通过 Map -> MapKey 隐藏(阴影) FK名称来覆盖该行为。 c>流畅的配置:

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"));

更新:请注意隐藏(阴影) HasForeignKey 流利的方法,而将 ForeignKey 属性线索错误。因此,如果您在 ChildProject 类中有这样的内容:

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.

这篇关于如何以一对一/零关系指定外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆