【问题标题】:Entity framework multiple one-to-one relations实体框架多重一对一关系
【发布时间】:2015-04-24 06:08:51
【问题描述】:

我在将外键设置为引用三个可能实体之一的实体时遇到问题。类如下:

public class Target
{
    public int Id { get; set; }
    public int? AttachmentId { get; set; }
    public virtual Attachment Attachment { get; set; }
}
public class SubTarget
{
    public int Id { get; set; }
    public int? AttachmentId { get; set; }
    public virtual Attachment Attachment { get; set; }
}
public class Procedure
{
    public int Id { get; set; }
    public int? AttachmentId { get; set; }
    public virtual Attachment Attachment { get; set; }
}
public class Attachment
{
    public int Id { get; set; }
    public int? TargetId { get; set; }
    public int? SubTargetId { get; set; }
    public int? ProcedureId { get; set; }
    public virtual Target Target { get; set; }
    public virtual SubTarget SubTarget { get; set; }
    public virtual Procedure Procedure { get; set; }
}

因此,三个第一类中的每一个都可能有也可能没有Attachment,每个Attachment 可以而且必须引用三个第一类中的一个。
首先:是有可能有这样的外键设置吗?
其次:我如何通过代码优先迁移来完成它?
在当前设置下,我收到一条错误消息,指出“无法确定外键关系的主体端”,并且通过注释掉 Attachment 类中的虚拟属性,关系似乎倒退了,即。 Target 有一个引用 Attachment 的外键。

【问题讨论】:

标签: c# entity-framework ef-code-first entity-framework-6


【解决方案1】:

如果您想在 EF 中建立一对一的关系,请将此注释添加到 Target、SubTarget 和 Procedure 类:

[Key, ForeignKey("Attachments")]
public int Id {get;set;}

这将使主键与外键相同。 然后从这 3 个类中删除:

 public int? AttachmendId {get;set;}

希望你能得到这份工作。我通常经常为一对一的关系而苦苦挣扎,所以我基本上会将我的表设计为一对零或一对多。 如果您需要有关一对一关系的更多信息:看这里 Entity framework multiple one-to-one relations

【讨论】:

  • 试过了,但它并没有像人们想象的那样发挥作用。我在表中还有其他几个 FK 关系,而且此时更改架构并不是那么简单。但是,我也怀疑这种解决方案会导致Attachment 必须引用所有其他 3 个类。
  • 我用这些属性重建了数据库,正如我所想,它现在需要 Attachment 类上的所有 3 个引用。所以,没有任何帮助..
  • 如果你只是删除所有引用回附件呢?只有那些其他类的附件外键?
猜你喜欢
  • 2013-11-24
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多