imperialx
imperialx

Reputation: 143

Using EF6 code-first, reference same property name

How to reference both ShippingAddressId and BillingAddressId properties in Customer class to Address class which has a diffrent key named AddressId?

Running update-database -verbose causes error:

Unable to determine the principal end of an association between the types 'Project1.Customer' and 'Project1.Address'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public int ShippingAddressId { get; set; }
    public int BillingAddressId { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public string StateProvince { get; set; }
    public string Zip{ get; set; }
    public string Country { get; set; }

    public virtual Customer Customer { get; set; }
}

Upvotes: 1

Views: 76

Answers (1)

Szer
Szer

Reputation: 3476

public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    public virtual Address ShippingAddress { get; set; }
    public int ShippingAddressId { get; set; }

    public virtual Address BillingAddress { get; set; }
    public int BillingAddressId { get; set; }
}

public class Address
{
    public int AddressId { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public string StateProvince { get; set; }
    public string Zip { get; set; }
    public string Country { get; set; }

    public ICollection<Customer> CustomersWhereShipping { get; set; }
    public ICollection<Customer> CustomersWhereBilling { get; set; }
}

You alse have to add custom logic to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .HasRequired<Address>(c => c.BillingAddress)
        .WithMany(a => a.CustomersWhereBilling)
        .HasForeignKey(c => c.BillingAddressId);

    modelBuilder.Entity<Customer>()
        .HasRequired<Address>(c => c.ShippingAddress)
        .WithMany(a => a.CustomersWhereShipping)
        .HasForeignKey(c => c.ShippingAddressId);
}

Upvotes: 1

Related Questions