为什么拥有类型的集合会生成一个 Id,我该如何避免这种情况?

Why collections of owned types generate an Id and how can I avoid that?

正如微软所说 here :

Owned entities are essentially a part of the owner and cannot exist without it, they are conceptually similar to aggregates

这意味着在 DDD 架构(领域驱动设计)中,我们可以使用拥有类型(或拥有类型的集合)作为聚合内的实体或值对象。另一方面,我们知道 DDD 中的 ValueObject 由于其结构和 Immutability 而没有 Identity 值。我想知道如果我决定使用 Owned 类型来实现值对象,我该如何强制它避免在创建时创建 Id table?

例如,正如您在下图(微软提到 here)中看到的,当我们使用拥有类型的集合时,EF 在 table 中创建了一个“Id”字段,没有地址值对象中的意义!如何避免?这真的是一个正确的选择吗?

那个例子来自 OwnsMany 场景,它清楚地解释了它需要 table 中的 FK 来关联地址 es 返回给他们的经销商。在加载实体时,地址记录如何关联回分发者?

如果分销商只有 0-1 个地址,那么您不需要地址上的 OwnerId,地址的 ID 列将作为 PK 和 FK 返回给分销商。 EF 需要每个 table 上的“键”来唯一标识每一行。您可以通过映射复合键来避免“Id”列,本质上:

public class Address
{
    [Key, Column(0), ForeignKey("Owner")]
    public int OwnerId { get; set; }
    [Key, Column(1)]
    public string Street { get; set; }
    [Key, Column(2)]
    public string City { get; set; }

    public virtual Distributor Owner { get; set; }
}

地址的专用唯一和数据库生成的 Id 列 table IMO 比字符串和 FK 的大型复合键更有意义。

就数据库而言,所有权在模式布局方式和关系规则方面与 HasOne / HasMany 相同。 OwnsManyHasMany 的区别在于 EF 允许您访问那些拥有的实体的方式。您不能拥有 DbSet<Address>,只能通过它的分销商访问地址。除了解决特定的设计模式问题外,它没有任何实际用途。 :)