2015-06-22 78 views
1

如何將Customer類中的ShippingAddressId和BillingAddressId屬性引用到Address類,該類具有名爲AddressId的不同關鍵字?使用EF6代碼優先,參考相同的屬性名稱

運行更新的數據庫-verbose導致錯誤:

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; } 
} 
+0

如果兩個客戶住在同一個地址?例如男人,妻子,女兒,兒子等 –

+0

你在做任何編碼創建任何引用或只依靠默認行爲? –

回答

1
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; } 
} 

您ALSE必須自定義邏輯添加到您的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); 
} 
+0

謝謝Szer,這很有效。我不知道優先級對虛擬資產非常重要。 – imperialx

相關問題