在 EF-Core 2 中处理多对多关系时的 CRUD 操作

CRUD operation while working with many to many relationships in EF-Core 2

我目前正在阅读一个博客,其中有一个关于书籍和作者的多对多关系的示例 asp.net 核心。

public class Book               
{
    public int BookId { get; set; }   
    public string Title { get; set; }    
    public string Description { get; set; }
    public List<BookAuthor> AuthorLink { get; set; }
}

public class Author               
{
    public int AuthorId { get; set; }   
    public string Name { get; set; }    
    public List<BookAuthor> { get; set; }
}

public class BookAuthor               
{
    public int BookId { get; set; }   
    public int AuthorId { get; set; } 

    public Book Book { get; set; }    
    public Author Author { get; set; }
}

而insert方法是这样写的:

var book = new Book
{
  Title = "Quantum Networking",
  Description = "faster-than-light data communications",
  PublishedOn = new DateTime(2057, 1, 1),
  Price = 220
};
var author = new Author { Name = "Future Person" };
book.AuthorsLink = new List<BookAuthor>
{
  new BookAuthor {  // WHAT IF THERE ARE MULTIPLE AUTHORS?
    Author = author, 
    Book = book,
    Order = 0
  }
};

如何插入多个逗号分隔的作者?我应该在 book.AuthorLink

中使用 "foreach" 循环吗

既然您已经扩展了模型(这是解决方案的一部分!),您可以使用列表初始化程序初始化列表:

book.AuthorsLink = new List<BookAuthor>
{
  new BookAuthor {
    Author = author, 
    Book = book,
    Order = 0
  },
  new BookAuthor {
    Author = author2, 
    Book = book,
    Order = 0
  },
  new BookAuthor {
    Author = author3, 
    Book = book,
    Order = 0
  }
};

或者只是初始化空列表,然后是一系列的book.AuthorsLink.Add(someAuthor)