Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding "id" properties where there are navigation properties (EF)

If I have a navigation property (ie: virtual), for example:
public virtual User Author { get; set; }

And I want to have also the id of that User, ie:
public int AuthorId { get; set; }

How can I tell EF that this "AuthorId" must be related to the Author property?

I don't like the idea of this being automatic (EF magically deducing this).
Because one could have multiple references to the same table:

public virtual User Author { get; set; }
public int AuthorId { get; set; }
public virtual User Receiver { get; set; }
public int ReceiverId { get; set; }
like image 768
sports Avatar asked Sep 04 '12 20:09

sports


1 Answers

Entity framework will assume that the AuthorID is the FK of the Author class. See this blog post for the details.

You could also explicitly tell EF, by using data annotations:

[ForeignKey("Author")]
public int AuthorId {get;set;}

or by using fluent mappings:

modelBuilder.Entity<YourClass>().HasRequired(p => p.Author)
                .WithMany()
                .HasForeignKey(p => p.AuthorId);
like image 183
Mark Oreta Avatar answered Oct 12 '22 09:10

Mark Oreta