【发布时间】:2018-07-18 16:16:04
【问题描述】:
我在数据库中有 2 个表:ReceivedGoods 和 ReceivedGoodsProperties
ReceivedGoods 包含 ReceivingId 作为 PK 并且必须在 ReceivedGoodsProperties 中包含其扩展数据,其中包含 ReceivingId 作为 FK 引用 ReceivedGoods 的 ReceivingId。然而,当前ReceivedGoodsProperties 有自己的 PK Id,因此与 FK 不同。所以我有以下几点:
public class ReceivedGoods
{
...
public int ReceivingId { get; set; }
...
public virtual ReceivedGoodsProperties properties { get; set; }
}
public class ReceivedGoodsProperties
{
...
public int Id { get; set; } // This is PK
public int ReceivingId { get; set; } // This is FK
...
public virtual ReceivedGoods goods { get; set; }
}
我想获取ReceivedGoods 对象并自动加载属性,但我不知道如何在 EF 中设置它。
我尝试过这样的事情(来自ReceivedGoodsProperties 侧映射):
this.HasRequired(p => p.goods)
.WithRequiredDependent(d => d.properties)
.Map(m => m.MapKey("ReceivingId"));
但我最终会遇到以下错误:
ReceivingId: Name: Each property name in a type must be unique. Property
name 'ReceivingId' is already defined.
在ReceivedGoodsProperties 中注释掉ReceivingId 时,不抛出上异常,ReceivedGoods 被正确加载,除了properties 属性。
谁能解释一下,在这种情况下如何进行一对一的映射?
【问题讨论】:
-
就我个人而言,我会让 FK 成为 PK。是否有理由需要单独的 PK?我能想到的唯一原因是,如果您想要一对零或一对关系,那么您的 FK 需要可以为空。
-
不幸的是我已经设计好了数据库。 1 到 0 或 1 不是我的情况,但我不确定现在是否可以更改 PK。
标签: c# entity-framework-6 one-to-one ef-fluent-api