[英]How to implement many to many relationship in ASP.NET CORE WEB API
所以我有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] 請求編寫 Function ,以便它像這樣返回 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)讓我感到困惑。
對於返回的 json 格式,可以先通過Include
和ThenInclude
獲取所有關聯數據。
然后使用Select
方法和新對象組成返回的數據結構:
public IActionResult ReturnJson()
{
var data = _context.Book.Include(x => x.Author)
.Include(x => x.BookCategories).ThenInclude(x => x.Category)
.Select(x => new
{
bookId = x.BookId,
title = x.Title,
authorName = x.Author.Name,
authorSurname = x.Author.Surname,
categories = x.BookCategories.Select(k => k.Category.CategoryName).ToList()
});
return Json(data);
}
這是返回的數據:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.