[英]Many to Many relation using fluent api EF Core 5
我想我有兩個具有多對多關系的實體,我將使用流利的 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 中的多對多中進行了描述
要更改列名:
...
b => b.HasOne<Author>().WithMany().HasForeignKey("AuthorId "),
b => b.HasOne<Book>().WithMany().HasForeignKey("BookId"));
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.