在单个实体中能否拥有同基类(TPH)实体的多个集合属性?
Absolutely! You can absolutely have multiple collection properties of derived TPH entities on a single parent entity in EF Core 2.0, but you need to explicitly configure the relationships using Fluent API to help EF Core distinguish between the two associations—otherwise, it’ll get confused by the shared base class and navigation property.
Here’s how to set this up correctly for your code:
Step 1: Configure the TPH Discriminator
First, define the discriminator column that EF Core uses to differentiate between AudioLink and VideoLink records in the single Links table:
protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configure TPH discriminator for the Link base class modelBuilder.Entity<Link>() .HasDiscriminator<string>("LinkType") .HasValue<AudioLink>("Audio") .HasValue<VideoLink>("Video"); }
Step 2: Explicitly Map Each Collection Relationship
Next, you need to tell EF Core that each collection on Site is associated with a specific derived type, using the same SiteId foreign key but distinct constraints to avoid conflicts:
protected override void OnModelCreating(ModelBuilder modelBuilder) { // ... (discriminator config from above) // Map Site.AudioLinks to AudioLink modelBuilder.Entity<Site>() .HasMany(s => s.AudioLinks) .WithOne(l => l.Site) .HasForeignKey(l => l.SiteId) .HasConstraintName("FK_AudioLinks_Sites") // Unique constraint name .OnDelete(DeleteBehavior.Cascade); // Map Site.VideoLinks to VideoLink modelBuilder.Entity<Site>() .HasMany(s => s.VideoLinks) .WithOne(l => l.Site) .HasForeignKey(l => l.SiteId) .HasConstraintName("FK_VideoLinks_Sites") // Unique constraint name .OnDelete(DeleteBehavior.Cascade); }
Key Notes:
- Why explicit config is needed: By default, EF Core would treat both
AudioLinksandVideoLinksas collections of the baseLinktype, leading to ambiguous relationship mappings. Specifying the derived type for each collection clarifies EF’s mapping logic. - Shared Foreign Key: Since both derived types inherit
SiteIdfromLink, you can reuse this column for both relationships—just make sure the constraint names are unique (as shown above) to avoid database schema conflicts. - Discriminator Requirement: The discriminator is mandatory for TPH in EF Core; it’s how EF knows which derived type to instantiate when reading records from the table.
With this configuration, EF Core will correctly map your Site entity’s two collections, storing all AudioLink and VideoLink records in the same table (TPH) while maintaining separate associations to their parent Site.
内容的提问来源于stack exchange,提问作者OL.

