Wednesday, May 15, 2019

[EF - Code-First] One-to-One Relationship issue

Hello guys, this should be quite a straight forward thing (and there's a lot of examples for this) but for some reason, I cannot figure out what I'm doing wrong... To add some context, imagine, for example, the following classes:

public class Archive{ [Key] public int ArchiveId { get; set; } //a few other irrelevant properties public virtual File specific_file; public virtual ICollection<File> other_files; //that can include the specific one } 

and

public class File{ [ForeignKey("Archive")] public int FileId { get; set; } //a few other irrelevant properties public virtual Archive archive; //#1 commented below } 

So, if this was a simple one-to-many relationship, EF would know what to do and attribute an FK automatically to File, and the line at #1 wouldn't be necessary.

But now, not only I need a one-to-many relationship, I also need to store a specific file (in this context) in the Archive Model. Previously, I tried by just adding "public virtual File specific_file;" to the Archive class and leave the File class unchanged, but after attempting to update the database, EF no longer knows who is the dependent class and is ALWAYS creating an FK in the Archive class, when I'm specifically stating that File should be the dependent class (and want to use the auto-generated FK that File has).

What am I doing wrong? Does anyone know a quick way to fix this issue?

Thank you very much, and have a great weekend

[EF - Code-First] One-to-One Relationship issue Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team