简体   繁体   English

实体框架-父母不同的孩子

[英]Entity Framework - Child with different parents

I am using EF 6, Code First. 我正在使用EF 6,Code First。 I have a "contact" entity, a "customer" and a "manufacturer". 我有一个“联系”实体,一个“客户”和一个“制造商”。 Both customer and manufacturer have a list of contact entities. 客户和制造商都有联系实体列表。 Maybe during development there can be more entities with a list of contact entities. 也许在开发过程中,可能会有更多具有联系实体列表的实体。 How do I shape the contact entity so I do not have a separate Id as foreign key for customer and manufacturer? 我如何塑造联系实体,以便没有单独的ID作为客户和制造商的外键? What I have in mind is something like: 我想到的是这样的:

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

    public int ParentId { get; set; }

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

    [ForeignKey("ParentId")]
    public virtual Manufacturer Manufacturer { get; set; }
}

Is this possible? 这可能吗?


EDIT: Seems that it is not that easy. 编辑:似乎并不是那么容易。 What I did was the following: 我所做的如下:

public class Customer 
{
    ...
    [InverseProperty("Customer")]
    public virtual ICollection<Contact> Contacts { get; set; }
    ....
}

public class Manufacturer
{
    ...
    [InverseProperty("Manufacturer")]
    public virtual ICollection<Contact> Contacts { get; set; }
    ...
}

public class Contact
{
    public int? ParentId { get; set; }

    [ForeignKey("ParentId")]
    public virtual Manufacturer Manufacturer { get; set; }

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

Now I have to include both manufacturer AND customer not manufacturer OR customer. 现在,我必须同时包括制造商和客户,而不是制造商或客户。 Putting an "...HasOptional(...)" in ModelBuilder did not solve the problem. 在ModelBuilder中放入“ ... HasOptional(...)”并不能解决问题。

???? ????

You need to use the InverseProperty attribute on your customer and manufacturer fields, eg 您需要在客户和制造商字段上使用InverseProperty属性,例如

[InverseProperty("Id")]
[ForeignKey("ParentId")]
public virtual Customer Customer { get; set; }

Read about it here. 在这里阅读。

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

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