与PK不同的FK一对一关系



我在数据库中有 2 个表:ReceivedGoodsReceivedGoodsPropertiesReceivedGoods包含ReceivingId作为PK,并且必须将其扩展数据包含在ReceivedGoodsProperties中包含ReceivingId引用ReceivedGoodsReceivingId的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时,不会抛出上部异常,ReceivedGoodsproperties属性外,加载正确。

有人可以解释一下,在这种情况下如何进行一对一映射吗?

你能试试吗:

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 成员,所以GoodsProperties

尝试以这种方式定义关系:

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

相关内容

  • 没有找到相关文章

最新更新