25

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..

2 Answers 2

45

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"));
   
2
  • @KonradViltersten There is a way - stackoverflow.com/questions/65779730/…, 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, 2021 at 13:11
  • I'll go with this 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. Nov 14, 2021 at 13:43
6

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"));
3
  • 2
    if you install EF Core Providers for example Microsoft.EntityFrameworkCore.SqlServer then you don't need to install that package Jan 2, 2021 at 14:00
  • Correct, but you don't install that by default. I only had EF Core package. Jan 2, 2021 at 14:04
  • 4
    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 2, 2021 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.