How to customize join table name AND primary key names in EF Core 6?

Viewed 24

I wanted to customize the join table and primary key fields in EF Core 6 Migrations using Fluent API when it generates this based on the relationships defined below.

public class Product
{   
    public int ProductId { get; set; }
    public string Name { get; set; }
    public List<Part> Parts { get; set; }
}

public class Part
{
    public int PartId { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; }
}

When I use the Fluent API in DBContext OnModelCreating

 builder.Entity<Part>()
    .HasMany(left => left.Products)
    .WithMany(right => right.Parts)
    .UsingEntity(join => join.ToTable("ProductParts")
    );

It creates the many-to-many join table as follows

CREATE TABLE [dbo].[ProductParts](
[PartsPartId] [int] NOT NULL,
[ProductsProductId] [int] NOT NULL

I wanted to name the keys just "ProductId" and "PartId" without the prefixes. Can you name the keys if you're using ToTable and not using an explicit entity join class?

0 Answers
Related