Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Entity Framework Core creates unnecessary foreign key for owned type when using TPT mapping strategy #33591

Open
vasicvuk opened this issue Apr 22, 2024 · 1 comment

Comments

@vasicvuk
Copy link

File a bug

I found the original issue on Stackoverflow here:

https://stackoverflow.com/questions/75614840/entity-framework-core-creates-unnecessary-foreign-key-for-owned-type-when-using

I have the same issue, so I am pasting issue here:

When I configure any owned type in TPT child entity, ef creating additional foreign key to parent table.
I have configuration like this:

modelBuilder.Entity<TransportBase>(e => {
  e.UseTptMappingStrategy();
  e.ToTable("transports");
})
modelBuilder.Entity<Car>(e => {
  e.OwnsOne(x => x.MaxSpeed, bld =>
  {
    bld.Property(x => x.Value)
      .UsePropertyAccessMode(PropertyAccessMode.Field)
      .HasColumnName("max_speed");
  });
  e.HasBaseType<TransportBase>();
  e.ToTable("cars"));
})

And it generates these constraints in table "cars":

constraints: table =>
                {
                    table.PrimaryKey("PK_cars", x => x.id);
                    table.ForeignKey(
                        name: "fk_cars_transports_id",
                        column: x => x.id,
                        principalTable: "transports",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "fk_transports_transports_id",
                        column: x => x.id,
                        principalTable: "transports",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Cascade);
                });

It is the same keys, except for the name.
As far as I could figure it out, this is because the key for owned-type points to the primary key for Car. But the Id field flies into TransportBase, so ef starts thinking the owner is in another table and creates a foreign key.
How can I fix it?

I tried to set shadow property, which will be principal key, but it creates unnecessary columns in table.

@AndriySvyryd
Copy link
Member

Please try EF 9.0.0-preview.3.24172.4

If you are still experiencing the issue share a small runnable project that shows it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants