Many to Many relation using fluent api EF Core 5

6.1k Views Asked by At

I suppose I have the two entities with many to many relationships, and i am going to use fluent api to resolve this relationship

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public ICollection<Author> Authors { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{  
   //Book
    modelBuilder.Entity<Book>().HasKey(x => x.BookId);
    modelBuilder.Entity<Book>().Property(x => x.Title).IsRequired();

    //Author
    modelBuilder.Entity<Author>().HasKey(x => x.AuthorId);
    modelBuilder.Entity<Author>().Property(x => x.Name).IsRequired();

    //many to many relationship
    modelBuilder.Entity<Book>()
                .HasMany(x => x.Authors)
                .WithMany(x => x.Books);
}

Using ef core 5 we dont need to create a new entity. The problem is in my database now i have a table with the name

AuthorBook

with two columns

AuthorsAuthorId and BooksBookId.

How can change the name of the new table and the name of two columns? Also is the right way to resolve this relationship?

modelBuilder.Entity<Book>()
                    .HasMany(x => x.Authors)
                    .WithMany(x => x.Books);
2

There are 2 best solutions below

0
On

To change the column name:

   ...
   b => b.HasOne<Author>().WithMany().HasForeignKey("AuthorId "),
   b => b.HasOne<Book>().WithMany().HasForeignKey("BookId"));
   ...

see Entity Framework Core Many to Many change navigation property names

0
On

Changing the Many To Many table name and foreign keys columns is possible with UsingEntity in the following way:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{  
   //Book
    modelBuilder.Entity<Book>().HasKey(x => x.BookId);
    modelBuilder.Entity<Book>().Property(x => x.Title).IsRequired();

    //Author
    modelBuilder.Entity<Author>().HasKey(x => x.AuthorId);
    modelBuilder.Entity<Author>().Property(x => x.Name).IsRequired();

     modelBuilder.Entity<Book>().HasMany(
            x => x.Authors).WithMany(x => x.Books).
            UsingEntity<Dictionary<string, object>>(
                "M2MTable",
                b => b.HasOne<Author>().WithMany().HasForeignKey("AuthorId"),
                b => b.HasOne<Book>().WithMany().HasForeignKey("BookId"));
}

Result: DB Data

It was described on Entity Framework Community Standup - August 19th 2020 - Many-to-Many in EF Core 5.0