I'm trying to build a REST API. I have been using this guide by Microsoft Docs and I'd appreciate some help.
I have 2 models Library and Book. Each have their own controllers as well.
I want each to reference each other so I can get all books within a library and I want a book to reference what library it belongs to. I am using an in-memory database by Microsoft Entity Framework
My current model classes look like this:
Library:
public class Library
{
[Key]
public long id { get; set; }
public Book[] bookArray { get; set; }
public string postalCode { get; set; }
public string street { get; set; }
public string city { get; set; }
public string country { get; set; }
}
Book:
public class Book
{
[Key]
public long id { get; set; }
public long libraryId { get; set; }
public string title { get; set; }
public string author { get; set; }
public string description { get; set; }
}
I want a GET endpoint like so "api/Libraries/{id}/books" that will return the array of books within a library as JSON, but I can't return the array. I get the error "Can't implicitly convert Models.Book to Microsoft.AspNetCore.Mvc.ActionResult<A2.Models.Library>". Have I setup the model classes correctly? and how do I resolve this error.
The Code:
// GET: api/Libraries/5/books
[HttpGet("{id}/books")]
public async Task<ActionResult<Library>> GetLibraryBooks(long id)
{
var library = await _context.Libraries.FindAsync(id);
if (library == null)
{
return NotFound();
}
return library.bookArray;
}