c# - 与 FK 的一对一关系不同于 PK

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

我在数据库中有 2 个表:ReceivedGoodsReceivedGoodsProperties ReceivedGoods 包含作为 PK 的 ReceivingId 并且必须在 ReceivedGoodsProperties 中包含其扩展数据,其中包含 ReceivingId 作为引用 ReceivedGoodsReceivingId。但是,当前的 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 成员,因此 GoodsProperties

关于c# - 与 FK 的一对一关系不同于 PK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406698/

相关文章:

C# - 使用 RGB 值在颜色对话框中设置自定义颜色

c# - 手动创建字符串资源文件不适用于应用程序

c# - SAP 连接器 3.0 .NET 在表结构上设置值

java - Spring Data JDBC org.springframework.data.mapping.MappingException : Could not read value rental_movie from result set

nhibernate - 这个单向NHibernate一对一映射怎么做?

c# - 创建 Word 文档并从 .NET 应用程序添加图像

c# - Entity Framework 复合主键-如何获取列的顺序

c# - EF6 - 没有做我对 .Any() 的预期

c# - 什么约定将 poco 属性自动映射到列?我怎样才能禁用该自动映射?

mysql - 与共享的一对一关系在执行时不起作用