Specifies custom foreign key name if a foreign key not following EF's convention is desired.
public class Person
{
public int IdAddress { get; set; }
[ForeignKey(nameof(IdAddress))]
public virtual Address HomeAddress { get; set; }
}
This can also be used when you have multiple relationships to the same entity type.
using System.ComponentModel.DataAnnotations.Schema;
public class Customer
{
...
public int MailingAddressID { get; set; }
public int BillingAddressID { get; set; }
[ForeignKey("MailingAddressID")]
public virtual Address MailingAddress { get; set; }
[ForeignKey("BillingAddressID")]
public virtual Address BillingAddress { get; set; }
}
Without the ForeignKey
attributes, EF might get them mixed up and use the value of BillingAddressID
when fetching the MailingAddress
, or it might just come up with a different name for the column based on its own naming conventions (like Address_MailingAddress_Id
) and try to use that instead (which would result in an error if you're using this with an existing database).