【发布时间】:2020-11-26 21:12:25
【问题描述】:
所以我有 4 个班级:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
我想为 [HttpGet] 请求编写函数,以便它返回如下 JSON:
[
{
"bookId": "1",
"title": "Book Title 1",
"authorName": "Author Name 1",
"aurhorSurname": "Author Surname 1",
"categories": ["category1", "category2"]
},
{
"bookId": "2",
"title": "Book Title 2",
"authorName": "Author Name 1",
"aurhorSurname": "Author Surname 1",
"categories": ["category2", "category3"]
},
{
"bookId": "3",
"title": "Book Title 3",
"authorName": "Author Name 1",
"aurhorSurname": "Author Surname 1",
"categories": ["category1", "category4"]
},
]
我知道如何处理一对多的关系,并且我为作者和书籍创建了 API,其中每个作者都有自己写的一系列书籍。但是这个连接表(BookCategory)让我很困惑。
【问题讨论】:
-
你有没有尝试过?文档对这些东西有很好的描述:docs.microsoft.com/en-us/ef/core/modeling/…
-
这里有很多假设:从 dbContext 中获取书籍,包括 BookCategories。映射到视图模型时,只需将类别名称选择到一个数组中,这就是模型所期望的。
标签: c# asp.net .net asp.net-core entity-framework-core