C# 在EF Core 2中处理多对多关系时执行CRUD操作
我目前正在读一个博客,其中有一个关于asp.NETCore中书籍和作者的多对多关系的例子C# 在EF Core 2中处理多对多关系时执行CRUD操作,c#,many-to-many,ef-core-2.1,C#,Many To Many,Ef Core 2.1,我目前正在读一个博客,其中有一个关于asp.NETCore中书籍和作者的多对多关系的例子 public class Book { public int BookId { get; set; } public string Title { get; set; } public string Description { get; set; } public List<BookAuthor> AuthorLink
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; }
}
插入方法写为:
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现在您已经扩展了作为解决方案一部分的模型!,您可以使用列表初始值设定项初始化列表:
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.AddsomeAuthor否否,您必须更改模型。目前,它不支持多个作者。编辑类,可能支持数组或authors@Attersson很抱歉我只是添加了完整的模型,以避免混淆。我添加了完整的答案,请注意,这不是混淆的问题,而是解决方案本身的一部分:我还更正了第6行,但请检查类书中的字段,它们与您的代码段不同。例如,发布者不存在,订单也不存在。