我在数据库中有 2 个表:ReceivedGoods
和 ReceivedGoodsProperties
ReceivedGoods
包含作为 PK 的 ReceivingId
并且必须在 ReceivedGoodsProperties
中包含其扩展数据,其中包含 ReceivingId
作为引用 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
外都正确加载了> 属性(property)。
谁能给我解释一下,在这种情况下如何进行一对一映射?
最佳答案
你能不能试试:
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
[ForeignKey( "goods " )]
public int ReceivingId { get; set; } // This is FK
...
[Required]
public virtual ReceivedGoods goods { get; set; }
}
顺便说一句,在 C# 中,标准指南适用于 PascalCase 成员,因此 Goods
和 Properties
关于c# - 与 FK 的一对一关系不同于 PK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406698/