EFCore 将 2 个实体映射到相同的 table - 无法添加新条目

EFCore Map 2 entities to same table - unable to add new entry

我有两个独立的聚合,比如 Group 和 Brand,这两者之间存在多对多关系。由于这是两个独立的聚合体,我分别创建了独立的桥接实体 BrandGroupGroupBrand。现在我想将这两个映射到相同的 table。两个实体都在 相同的 DbContext 下。以下是我的实体配置:

public class BrandGroupEntityTypeConfiguration : BaseEntityTypeConfiguration<BrandGroup>
{
    public override void Configure(EntityTypeBuilder<BrandGroup> brandGroupConfiguration)
    {
        base.Configure(brandGroupConfiguration);
        brandGroupConfiguration.ToTable("BrandGroup");
        brandGroupConfiguration.Property(bc => bc.GroupId).IsRequired().HasColumnName(nameof(BrandGroup.GroupId));
        brandGroupConfiguration.Property(bc => bc.BrandId).IsRequired().HasColumnName(nameof(BrandGroup.BrandId));
        brandGroupConfiguration.HasIndex(bc => new { bc.GroupId, bc.BrandId }).IsUnique().HasFilter("[Deleted] = 0");
        brandGroupConfiguration.HasOne<GroupBrand>().WithOne().HasForeignKey<BrandGroup>(b => b.Id);
    }
}


public class GroupBrandEntityTypeConfiguration : BaseEntityTypeConfiguration<GroupBrand>
{
    public override void Configure(EntityTypeBuilder<GroupBrand> groupBrandConfiguration)
    {
        base.Configure(groupBrandConfiguration);
        groupBrandConfiguration.ToTable("BrandGroup");
        groupBrandConfiguration.Property(gb => gb.GroupId).IsRequired().HasColumnName(nameof(GroupBrand.GroupId));
        groupBrandConfiguration.Property(gb => gb.BrandId).IsRequired().HasColumnName(nameof(GroupBrand.BrandId));
    }
}

但是,当我尝试添加没有相应品牌组的新品牌或组时,它保存得很好。但是,如果我尝试通过品牌或群组添加品牌-群组关系,则会 returns 出现错误:

The entity of type 'GroupBrand' is sharing the table 'Configuration.BrandGroup' with entities of type 'BrandGroup', but there is no entity of this type with the same key value that has been marked as 'Added'.

我不太确定我错过了什么。

Entity Framework 抱怨状态无效

基本上,它看到 BrandGroup 已添加,但 GroupBrand 中没有相同的实体。然而它们是相同的 table.

所以根据Entity Framework,有没有添加什么东西?如果它查看 BrandGroup,它可能会得出添加了某些内容的结论,但如果它查看 GroupBrand,则什么也没有添加。所以有冲突。

通常在多对多关系中,你会有这样的东西

       ╔════════════╗
Group ═╣ GroupBrand ╠═ Brand
       ╚════════════╝

因此 Brand 对象和 Group 对象都将具有 GroupBrand 个对象的集合。

因此,与其使用 GroupBrand 和 BrandGroup,不如选择其中之一。