简体   繁体   English

EF Core - 多个父母拥有同一个孩子的列表(代码优先)

[英]EF Core - multiple parents with a list of the same child (code first)

Is there any way to represent something like this:有什么方法可以表示这样的东西:

public abstract class DbEntity
{
    [Key]
    public string Id { get; set; } // <-- a GUID-String created by the domain
}

public class Carrier : DbEntity
{
    public string Name { get; set; } = default!;
    public ICollection<Address> Addresses { get; set; }
}

public class Customer : DbEntity
{
    public string Name { get; set; } = default!;
    public ICollection<Address> Addresses { get; set; }
}

public class Address
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string? Street { get; set; }
}

Entity Framework will always create the address-table like this:实体框架将始终像这样创建地址表:

  • Id ID
  • Street街道
  • CarrierId运营商编号
  • CustomerId客户ID

The problem is, that multiple tables will have an list of addresses (not just two) and I really don't want something like:问题是,多个表将有一个地址列表(不仅仅是两个),我真的不想要这样的东西:

  • Id ID
  • Street街道
  • Parent1Id Parent1Id
  • Parent2Id Parent2Id
  • Parent3Id Parent3Id
  • Parent4Id Parent4Id
  • ... ...

I've also tried to set up my entities like this:我也试过这样设置我的实体:

_modelBuilder?.Entity<Carrier>()
              .HasMany(entity => entity.Addresses);

Which will also create the navigation properties on the child.这还将在子项上创建导航属性。

I'm also understanding why, because its a many-to-one relationship and the child needs to know his parent.我也明白为什么,因为它是多对一的关系,孩子需要了解他的父母。

However I really have no ideas to solve my 'problem'.但是我真的没有办法解决我的“问题”。

I was thinking about creating multiple classes/tables for my addresses like 'CustomerAddress' and 'CarrierAddress' (which inheritance from 'address'), but creating a new address table for every parent.. feels wrong?我正在考虑为我的地址创建多个类/表,例如“CustomerAddress”和“CarrierAddress”(来自“地址”的 inheritance),但是为每个父母创建一个新的地址表......感觉不对?

Is this really the right way or can I solve this somehow else or is something considered 'good practise' for such cases?这真的是正确的方法吗,或者我能以其他方式解决这个问题,还是在这种情况下被认为是“良好做法”?

You can use Address class with a generic type, but this will generate multiple tables with different names like this:您可以将 Address class 与通用类型一起使用,但这会生成多个具有不同名称的表,如下所示:

Address<Parent1>
Address<Parent2>
Address<Parent3>

If this is ok with you, you can modify Address class as:如果您不介意,您可以将地址 class 修改为:

public class Address<TParent>
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string? Street { get; set; }
    public TParent Parent { get; set; }
}

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

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