【发布时间】:2017-06-24 05:30:23
【问题描述】:
我在 ASP.NET Core MVC 上使用 EF Core 使用 Web api 返回存储在 SQLLite 数据库中的 Book 的数据。
这里是 DbContext 代码:
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; }
}
}
这里是 web api 控制器代码:
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();
}
}
}
}
两个 GET 请求似乎都可以正常工作,POST 也是如此。 当我想添加一本新书时,我会发送一个 POST 请求,如下所示:
https://gyazo.com/e96c81479f7ccc084401d70cf13c4cbe
当我发送该请求时,我会得到我的数据,如下所示:
{
"bookId": 3,
"name": "A book on US Politics",
"author": {
"name": "Enra",
"authorId": 3
}
}
例如,当我尝试在 /api/books/3 上执行 GET 请求时,它会返回以下数据:
{
"bookId": 3,
"name": "A book on US Politics",
"author": null
}
我什至使用 SQLLite 浏览器检查了数据库并且数据存在。这对我来说没有意义。
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework