与FK的一对一关系不同于PK

时间:2018-07-18 16:16:04

标签: c# entity-framework-6 one-to-one ef-fluent-api

我在数据库中有2个表:ReceivedGoodsReceivedGoodsProperties ReceivedGoods包含ReceivingId作为PK,并且必须在ReceivedGoodsProperties中具有其扩展数据,其中ReceivingId包含ReceivedGoods的{​​{1}}作为FK。但是,当前的ReceivingId具有自己的PK ReceivedGoodsProperties,因此与FK不同。所以我有以下内容:

Id

我想获取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; } } 对象并具有自动加载的属性,但是我不知道如何在EF中进行设置。 我已经尝试过类似的操作(从ReceivedGoods侧面映射):

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. 中注释掉ReceivingId时,不会引发较高的异常,除了ReceivedGoodsProperties属性以外,ReceivedGoods已正确加载。

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

2 个答案:

答案 0 :(得分:0)

您可以尝试:

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

答案 1 :(得分:0)

尝试通过这种方式定义关系:

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