简体   繁体   English

实体框架多个一对一关系

[英]Entity framework multiple one-to-one relations

I have a problem with setting foreign keys to an entity which references one of three possible entities. 我将外键设置为引用三个可能实体之一的实体时遇到问题。 Classes are the following: 类别如下:

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

So, each of the three first classes may or may not have an Attachment , and each Attachment can and must reference one of the three first classes. 因此,三个第一类中的每个都可以具有或可以不具有Attachment ,并且每个Attachment可以并且必须引用三个第一类中的一个。
Firstly: Is it at all possible to have a foreign key setup like this? 首先:完全有可能具有这样的外键设置吗?
Secondly: How do i accomplish it with code-first migrations? 其次:如何通过代码优先的迁移来实现?
With the current setup I get an error stating "Unable to determine the principal end of foreign-key-relations", and by commenting out the virtual properties in the Attachment class, the relation seems to go backwards, ie. 在当前设置下,我收到一条错误消息,指出“无法确定外键关系的主要结尾”,并且通过注释掉Attachment类中的虚拟属性,该关系似乎向后退。 Target has a foreign key that references Attachment . Target具有引用Attachment的外键。

If you want to have one-to-one relation in EF, add to Target, SubTarget and Procedure classes this annotation to: 如果要在EF中具有一对一关系,请将此注释添加到Target,SubTarget和Procedure类中,以:

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

This will make Primary key same as Foreign Key. 这将使主键与外键相同。 Then remove from these 3 classes: 然后从以下3个类中删除:

 public int? AttachmendId {get;set;}

Hopefully you can get this work. 希望你能完成这项工作。 I've been usually struggling with one-to-one relations often, so I basically would design my tables as one-to-zero or one-to-many. 我通常经常在一对一关系中挣扎,因此我基本上将表设计为一对零或一对多。 If you need more information regarding one-to-one relations: look here Entity framework multiple one-to-one relations 如果您需要有关一对一关系的更多信息:请在此处查看实体框架多个一对一关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM