Reputation: 50
So I have 4 classes:
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; }
}
I want to write Function for [HttpGet] request, so that it returns JSON like this:
[
{
"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"]
},
]
I know how to handle One-to-many relathionships, and I created API for author and book where every author has an array of books that he wrote. But this join table (BookCategory) confuses me.
Upvotes: 0
Views: 1640
Reputation: 6881
For the returned json format, you can get all the associated data through Include
and ThenInclude
first.
Then use the Select
method and new objects to form the returned data structure:
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);
}
Here is the returned data:
Upvotes: 2