I'm using web api to return the data of a Book stored in an SQlLite database, using EF Core, on ASP.NET Core MVC.
Here is the DbContext code:
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Yara.SQLite
{
public class BookingContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
//public DbSet<Author> Authors { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=books.db");
}
}
public class Book
{
public int BookId { get; set; }
public string Name { get; set; }
public Author Author { get; set; }
}
public class Author
{
public string Name { get; set; }
public int AuthorId { get; set; }
}
}
and here is the web api controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Yara.SQLite;
namespace Yara.Controllers.API
{
public class UsersController : Controller
{
[HttpGet]
[Route("api/books")]
public IEnumerable<Book> GetBooks()
{
using(var c = new BookingContext())
{
return c.Books.ToList();
}
}
[HttpGet]
[Route("api/books/{id:int}")]
public Book GetBook(int id)
{
using(var c = new BookingContext())
{
return c.Books.FirstOrDefault(b => b.BookId == id);
}
}
[HttpPost]
[Route("api/books")]
public Book AddBook([FromBody] Book book)
{
using(var db = new BookingContext())
{
db.Books.Add(book);
db.SaveChanges();
return db.Books.Where(o => o == book).FirstOrDefault();
}
}
}
}
Both the GET requests seem to work fine, and so does the POST. When I want to add a new Book, I'll send a POST request, like so:
https://gyazo.com/e96c81479f7ccc084401d70cf13c4cbe
and when i send that request, I'll get my data, like so:
{
"bookId": 3,
"name": "A book on US Politics",
"author": {
"name": "Enra",
"authorId": 3
}
}
When I try to do a GET request on /api/books/3 for example, it'll return this data:
{
"bookId": 3,
"name": "A book on US Politics",
"author": null
}
I've even checked the database using SQLLite browser and the data exists. It doesn't make sense to me.