首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >与FK不同于PK的一对一关系

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

Stack Overflow用户
提问于 2018-07-19 00:16:04
回答 2查看 71关注 0票数 2

我的数据库里有两个表:ReceivedGoodsReceivedGoodsProperties ReceivedGoods包含ReceivingId作为PK,它的扩展数据必须在ReceivedGoodsProperties中包含ReceivingId作为FK引用ReceivedGoodsReceivingId。但是当前的ReceivedGoodsProperties有它自己的PK Id,因此不同于FK。所以我有以下内容:

代码语言:javascript
复制
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侧映射):

代码语言:javascript
复制
this.HasRequired(p => p.goods)
    .WithRequiredDependent(d => d.properties)
    .Map(m => m.MapKey("ReceivingId"));

但我最终得到了以下错误:

代码语言:javascript
复制
ReceivingId: Name: Each property name in a type must be unique. Property 
name 'ReceivingId' is already defined.

ReceivedGoodsProperties中注释掉ReceivingId时,不会引发上部异常,ReceivedGoods将正确加载( properties属性除外)。

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

EN

回答 2

Stack Overflow用户

发布于 2018-07-19 00:36:52

你能不能试试:

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2018-07-19 00:37:16

尝试这样定义关系:

代码语言:javascript
复制
this.HasRequired(p => p.goods)
    .WithRequiredDependent(p => p.properties)
    .HasForeignKey(p => p.ReceivingId);

如果您遵循标准的EF命名约定,它通常可以自己弄清楚这些关系。只有当您的导航属性名称与类名称不对应时,或者在源表中有多个指向同一目标的FK时,您才会真正遇到麻烦。

如果希望导航属性“自动”填充,请在查询上使用Include扩展方法,如:context.Goods.Include(g=>g.properties)。除非您想使用延迟加载,否则不必将它们声明为virtual

您可能需要从另一个实体获得此结果:

代码语言:javascript
复制
this.HasRequired(p => p.properties)
    .WithRequiredPrincipal(p => p.goods)
    .HasForeignKey(p => p.ReceivingId);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51406698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档