How can i map an existing foreign key to a navigation property with code first

168 views Asked by At

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 ?

1

There are 1 answers

0
tschmit007 On

AFAIK what you want can't be done with EF. Waht you seems to want is:

  1. one to one relation between Customer and Address, and
  2. one to many relation between Customer and Address.

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

modelBuilder.Entity<Customer>().
    HasOptional(x => x.MainBillingAddress). // or required
    WithMany(y => y.IsDefaultFor);

but this at least leads to circular refrences.