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

旧城冷巷雨未停 提交于 2021-01-27 07:10:20

问题


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


回答1:


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:


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"));


来源:https://stackoverflow.com/questions/64919574/change-name-of-generated-join-table-many-to-many-ef-core-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!