使用 EF6 代码优先,引用相同的 属性 名称

Using EF6 code-first, reference same property name

如何将 Customer class 中的 ShippingAddressId 和 BillingAddressId 属性引用到具有名为 AddressId 的不同键的地址 class?

运行 更新数据库-详细导致 错误:

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

您还必须向 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);
}