【问题标题】:Using EF6 code-first, reference same property name使用 EF6 代码优先,引用相同的属性名称
【发布时间】:2015-06-22 07:37:03
【问题描述】:

如何将 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; }
}

【问题讨论】:

  • 如果两个客户住在同一个地址怎么办?例如男人、妻子、女儿、儿子等
  • 你是在做任何编码来创建任何引用还是仅仅依赖默认行为?

标签: c# entity-framework properties mapping


【解决方案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);
}

【讨论】:

  • 谢谢 Szer,这行得通。我不知道优先级比虚拟属性更重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2015-12-04
相关资源
最近更新 更多