0

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;
        }

1 Answer 1

4

Your Method should return Book[] like this:

[HttpGet("{id}/books")]
    public async Task<ActionResult<Book[]>> GetLibraryBooks(long id)
    {
        var library = await _context.Libraries.FindAsync(id);

        if (library == null)
        {
            return NotFound();
        }

        return Ok(library.bookArray);
    }

UPDATE

public class Library
{
    public Libary(){
         books = new List<Book>();
    }

    [Key]
    public long id { get; set; }
    public List<Book> books { get; set; }
    public string postalCode { get; set; }
    public string street { get; set; }
    public string city { get; set; }
    public string country { get; set; }
}

UPDATE 2

    public class LibraryController : Controller
{
    private readonly LibraryContext _context;

    public LibraryController(LibraryContext context)
    {
        _context = context;
    }

    [HttpPost("{id}")]
    public IActionResult AddBookToLibrary([FromRoute]long id ,[FromBody] Book bookToAdd)
    {
        var libraryToAddBook = _context.Libraries.Include(l => l.books)
                                                 .FirstOrDefault(l => l.id == id);

        if (libraryToAddBook == null)
            return NotFound();

        libraryToAddBook.books.Add(bookToAdd);
        _context.SaveChanges();

        return Ok();
    }
}

UPDATED CONTEXT

    public class LibraryContext : DbContext
{
    public LibraryContext(DbContextOptions<LibraryContext> options)
        : base(options)
    {

    }

    public DbSet<Library> Libraries { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Library>()
            .OwnsMany<Book>(l => l.books);
    }

}

startup.cs

            var connectionString = Configuration.GetConnectionString("myDatabaseConnectionString");
        services.AddDbContext<LibraryContext>(options =>
        {
            //options.USEYOURDATABASE(connectionString); //you might need install a NuGet eg. Microsoft.EntityFrameworkCore.SqlServer
        });
Sign up to request clarification or add additional context in comments.

9 Comments

Ive forgot the Ok() ive added it to the answer
Wow, so bummed didn't notice that. Thanks! Are my models set up correctly?
Ive updated the model. I prefere lists because you can easy .Add(someBook) to your library its important to then initialize the list in an empty constructor
In your modelCreating, are you setting up a library to have only one book instance? I want a book to be able to belong in one library and a library can have multiple books. You've helped alot as it is, may I ask if you break down the code for me? How would I add a book to a llibrary from a post request (adding a book to a particular library). Thanks in advance.
Ive updated the code sinppets i hope its clear to you
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.