I'm using code first to create an application of customer management. A customer can have many addresses but only one "main" address.
Here is my Customer model :
public class Customer
{
[Key]
public int Id { get; set; }
public string FirstName{ get; set; }
public string LastName{ get; set; }
public int MainInvoicingAddressId { get; set; }
[ForeignKey("MainBillingAddressId")]
public Address MainBillingAddress { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
And my Address Model :
public class Address
{
[Key]
public int Id { get; set; }
public string Address1 { get; set; }
public int CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
But when i create the database, i have a auto generated foreign key Customer_Id on addresses table because of the navigation property MainBillingAddress.
So on addresses table, i have 2 foreign keys to Customer ("CustomerId" and "Customer_Id").
What i want is to use the existing foreign Key "CustomerId" for the relation with the MainBillingAddress.
Is it possible ?
AFAIK what you want can't be done with EF. Waht you seems to want is:
This can't be done because, with EF, 1. implies FK <=> PK. (for example), that is not compatible with 2..
I humbly suggest you read How to implement a one-to-many relationship with an "Is Current" requirement and replace the "Is Current" by "Is main".
I can imagine another solution like
but this at least leads to circular refrences.