c# - 使用流利的 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);
解决方案
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 中的多对多中进行了描述
推荐阅读
- azure - 当我从 Azure Devops 运行 az role assignment list 时,为什么看不到 Principal Name?
- azure-cognitive-search - Azure 搜索服务中的文档更新策略
- javascript - 需要帮助在 if 语句中设置逻辑运算符
- amazon-web-services - 如何配置安全组以允许 ECS 容器实例访问 VPC 中的 Aurora RDS?
- vue.js - vue-cli-service:在构建项目时选择要包含/排除的文件夹
- javascript - 如何过滤(搜索)R DT(DataTable)中的格式化列
- linux - (已关闭)apt-get 更新错误(sury.org)[linux]
- react-styleguidist - react-styleguidist 可以支持导出markdown吗
- python - 如何在 AWS Lambda 函数中包含库的子目录
- spring - 动态获取 CDI bean,而不是通过注入