26

How to change name of a join table that EF Core 5 Created ?

for example

 public class Food 
    {
        public int FoodId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Ingredients { get; set; }
        public string PhotoPath { get; set; }
        public ICollection<Menu> Menus { get; set; }
    }

  public class Menu
    {
        public int MenuId { get; set; }
        [Column(TypeName = "date")]
        public DateTime MenuDate { get; set; }
        public bool IsPublished { get; set; }
        public ICollection<Food> Foods { get; set; }
    }

and the join table for this 2 entities named FoodMenu, I want to change it to something else..

Armin Shoeibi
  • 580
  • 6
  • 18

2 Answers2

47

You can use one of the UsingEntity method overloads, for instance UsingEntity(Action<EntityTypeBuilder>).

Since it is a relationship fluent configuration API, you first need HasMany + WithMany pair, e.g.

modelBuilder.Entity<Food>()
    .HasMany(left => left.Menus)
    .WithMany(right => right.Foods)
    .UsingEntity(join => join.ToTable("TheDesiredName"));
   
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • @KonradViltersten There is a way - https://stackoverflow.com/questions/65779730/manytomany-relation-in-ef-core-fluent-api/65780863#65780863, but I wouldn't call it "clever" :-) Haven't checked it the fresh EFC 6.0 has improved it (there were some plans, not sure if they made it). – Ivan Stoev Nov 14 '21 at 13:11
  • I'll go with [this](https://stackoverflow.com/a/65046246/1525840) which apparently works now that I upgrades from 5.0.0 to 5.0.12 on the EF. Less than clever, indeed. (Well, maybe it is clever but unnecessarily verbose, IM!HO.) But at least working. And thanks for the reply. Appreciate that. – Konrad Viltersten Nov 14 '21 at 13:43
8

The accepted answer is missing an important part I had to struggle with.

First, you need to install the package

Microsoft.EntityFrameworkCore.Relational

Then you can add the following in your OnModelCreating overridden method

modelBuilder.Entity<Food>()
    .HasMany(left => left.Menus)
    .WithMany(right => right.Foods)
    .UsingEntity(join => join.ToTable("NameYouWish"));
Yahya Hussein
  • 8,767
  • 15
  • 58
  • 114
  • 2
    if you install EF Core Providers for example Microsoft.EntityFrameworkCore.SqlServer then you don't need to install that package – Armin Shoeibi Jan 02 '21 at 14:00
  • Correct, but you don't install that by default. I only had EF Core package. – Yahya Hussein Jan 02 '21 at 14:04
  • 5
    All `ToTable`, `HasColumnName` etc. fluent APIs require that package, nothing special for many-to-many configuration, hence no need to mention it explicitly. – Ivan Stoev Jan 02 '21 at 21:25