【问题标题】:How can i map an existing foreign key to a navigation property with code first如何首先使用代码将现有外键映射到导航属性
【发布时间】:2015-06-16 09:38:39
【问题描述】:

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

这是我的客户模型:

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 建立关系。

有可能吗?

【问题讨论】:

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


    【解决方案1】:

    AFAIK 无法用 EF 完成您想要的。你似乎想要的是:

    1. 客户和地址之间的一对一关系,并且
    2. 客户和地址之间的一对多关系。

    无法做到这一点,因为对于 EF,1. 意味着 FK PK。 (对于example),与2不兼容..

    我谦虚地建议您阅读How to implement a one-to-many relationship with an "Is Current" requirement 并将“Is Current”替换为“Is main”。

    我可以想象另一种解决方案,例如

    modelBuilder.Entity<Customer>().
        HasOptional(x => x.MainBillingAddress). // or required
        WithMany(y => y.IsDefaultFor);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2016-10-28
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多