繁体   English   中英

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

[英]Using EF6 code-first, reference same property name

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM