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

时间:2018-07-30 18:12:37

标签: c# many-to-many ef-core-2.1

我目前正在阅读一个博客,在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
  }
};

如何插入多个逗号分隔的作者?我是否应该在书内使用“ foreach”循环。AuthorLink

1 个答案:

答案 0 :(得分:1)

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

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)