简体   繁体   中英

C# REST API - returning an array as JSON

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM