Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change name of generated Join table ( Many to Many ) - EF Core 5

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

like image 690
Armin Shoeibi Avatar asked Nov 19 '20 20:11

Armin Shoeibi


People also ask

How do you create a many-to-many relationship in EF core?

Many-to-many. Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

How do you implement many-to-many relationship in code?

When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).


2 Answers

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"));
   
like image 163
Ivan Stoev Avatar answered Sep 23 '22 21:09

Ivan Stoev


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"));
like image 31
Yahya Hussein Avatar answered Sep 22 '22 21:09

Yahya Hussein