首页 > 解决方案 > 使用流利的 api EF Core 5 的多对多关系

问题描述

我想我有两个具有多对多关系的实体,我将使用 fluent api 来解决这种关系

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

使用 ef core 5 我们不需要创建新实体。问题出在我的数据库中,现在我有一个名称为的表

作者书

有两列

AuthorsAuthorId 和 BooksBookId。

如何更改新表的名称和两列的名称?也是解决这种关系的正确方法吗?

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

标签: c#entity-framework-coreef-core-5.0

解决方案


UsingEntity可以通过以下方式更改多对多表名和外键列:

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

结果: 数据库数据

它在Entity Framework Community Standup - 2020 年 8 月 19 日 - EF Core 5.0 中的多对多中进行了描述


推荐阅读