简体   繁体   中英

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.
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. Target has a foreign key that references Attachment .

If you want to have one-to-one relation in EF, add to Target, SubTarget and Procedure classes this annotation to:

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

This will make Primary key same as Foreign Key. Then remove from these 3 classes:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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