如何将Customer类中的ShippingAddressId和BillingAddressId属性引用到具有名为AddressId的差异键的Address类?
运行update-database -verbose导致错误:
无法确定之间关联的主要结束 类型' Project1.Customer'和' Project1.Address'。主要目的 必须使用以下任一方式显式配置此关联 关系流畅的API或数据注释。
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 :(得分: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; }
}
您还必须为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);
}