如何首先使用代码将现有外键映射到导航属性

时间:2015-06-16 09:38:40

标签: c# entity-framework ef-code-first code-first ef-model-first

我首先使用代码来创建客户管理应用程序。 客户可以拥有多个地址,但只有一个“主要”地址。

这是我的客户模型:

public class Customer
{
    [Key]
    public int Id { get; set; }

    public string FirstName{ get; set; }

    public string LastName{ get; set; }

    public int MainInvoicingAddressId { get; set; }

    [ForeignKey("MainBillingAddressId")]
    public Address MainBillingAddress { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }

我的地址模型:

    public class Address
    {
        [Key]
        public int Id { get; set; }

        public string Address1 { get; set; }

        public int CustomerId { get; set; }

        [ForeignKey("CustomerId")]
        public virtual Customer Customer { get; set; }
    }

但是当我创建数据库时,由于导航属性MainBillingAddress,我在地址表上有一个自动生成的外键Customer_Id。

因此,在地址表上,我有2个客户外键(“CustomerId”和“Customer_Id”)。

我想要的是使用现有的外键“CustomerId”来表示与MainBillingAddress的关系。

有可能吗?

1 个答案:

答案 0 :(得分:0)

AFAIK你想做什么不能用EF完成。你似乎想要的是:

  1. 客户与地址之间的一对一关系,
  2. 客户与地址之间的一对多关系。
  3. 这是不可能的,因为对于EF,1表示FK&lt; =&gt;。 PK。 (对于example),与2 ..

    不兼容

    我谦卑地建议你阅读How to implement a one-to-many relationship with an "Is Current" requirement并替换&#34; Is Current&#34; by&#34;主要是&#34;。

    我可以想象像

    这样的另一种解决方案
    modelBuilder.Entity<Customer>().
        HasOptional(x => x.MainBillingAddress). // or required
        WithMany(y => y.IsDefaultFor);
    

    但这至少会导致循环引用。