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; }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With