我在数据库中有 2 个表:ReceivedGoods
和ReceivedGoodsProperties
ReceivedGoods
包含ReceivingId
作为PK,并且必须将其扩展数据包含在ReceivedGoodsProperties
中包含ReceivingId
引用ReceivedGoods
ReceivingId
的FK作为FK。然而,目前的ReceivedGoodsProperties
有自己的PKId
,因此与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
属性外,加载正确。
有人可以解释一下,在这种情况下如何进行一对一映射吗?
你能试试吗:
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
尝试以这种方式定义关系:
this.HasRequired(p => p.goods)
.WithRequiredDependent(p => p.properties)
.HasForeignKey(p => p.ReceivingId);
如果遵循标准的 EF 命名约定,它通常可以自行找出这些关系。 仅当导航属性名称与类名不对应时,或者源表中有多个 FK 指向同一目标时,才会真正遇到麻烦。
如果希望"自动"填写导航属性,请在查询上使用Include
扩展方法,如:context.Goods.Include(g=>g.properties
)。您不必将它们声明为virtual
,除非您想使用延迟加载。
您可能需要从其他实体获得:
this.HasRequired(p => p.properties)
.WithRequiredPrincipal(p => p.goods)
.HasForeignKey(p => p.ReceivingId);