c# - GET 请求重置成员值
问题描述
尝试构建一个简单的 api,但遇到了一个问题,即成员在 GET 请求后似乎重置为默认值。有趣的是;我第一次发送请求时,会返回预期的结果,但是任何后续请求似乎都会导致一些数据丢失。为什么会这样?为什么第一个请求没有发生?我如何解决它?
(我使用的是 ASP.NET Core 2.2)
namespace RestaurantReviewApi.Controllers {
[Route("api/restaurants")]
[ApiController]
public class RestaurantsController : ControllerBase {
private readonly RestaurantContext _context;
public RestaurantsController(RestaurantContext context) {
_context = context;
// Create a new Restaurant if collection is empty
if(_context.Restaurants.Count() == 0) {
Restaurant firstRestaurant = new Restaurant {
Reviews = new List<Review> {
new Review { }
}
};
_context.Restaurants.Add(firstRestaurant);
_context.SaveChanges();
}
}
// GET: api/restaurants
[HttpGet]
public async Task<ActionResult<IEnumerable<Restaurant>>> GetRestaurants() {
return await _context.Restaurants.ToListAsync();
}
}
}
namespace RestaurantReviewApi.Models {
public class Restaurant {
public long Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<Review> Reviews { get; set; }
public double AverageRating { get; set; }
}
}
namespace RestaurantReviewApi.Models {
public class Review {
public long Id { get; set; }
public string Author { get; set; }
public string Text { get; set; }
public int Stars { get; set; }
}
}
namespace RestaurantReviewApi.Models {
public class RestaurantContext : DbContext {
public RestaurantContext(DbContextOptions<RestaurantContext> options) : base(options) { }
public DbSet<Restaurant> Restaurants { get; set; }
}
}
第一个请求(https://localhost:port/api/restaurants)给了我这个输出:
[
{
"id": 1,
"name": null,
"address": null,
"reviews": [
{
"id": 1,
"author": null,
"text": null,
"stars": 0
}
],
"averageRating": 0.0
}
]
随后的相同请求给出了这个:
[
{
"id": 1,
"name": null,
"address": null,
"reviews": null,
"averageRating": 0.0
}
]
解决方案:
[HttpGet]
public async Task<ActionResult<IEnumerable<Restaurant>>> GetRestaurants()
{
return await _context.Restaurants.Include(r => r.Reviews).ToListAsync();
}
解决方案
对于第一次请求,结果_context.Restaurants
是你的构造函数在控制器初始化时的值_context.Restaurants.Count() == 0
,而不是从数据库中查询。
对于后续相同的请求,您从数据库中查询餐厅。如果要查询相关数据,应使用Include
方法指定要包含在查询结果中的相关数据。
[HttpGet]
public async Task<ActionResult<IEnumerable<Restaurant>>> GetRestaurants()
{
return _context.Restaurants.Include(r=>r.Reviews).ToList();
}
参考:https ://docs.microsoft.com/en-us/ef/core/querying/related-data
推荐阅读
- python - wrap_socket() 得到了一个意外的关键字参数“_context”
- user-interface - 尽管我已连接到互联网,但我还是离线使用 Figma
- python - 切片字符串列表并填充字典值
- firebase - 如何正确处理 Firebase Cloud Functions 的幂等性?
- html - 为什么网格区域会缩小其他单元格,即使它有足够的空间?
- machine-learning - Yolo/SSD:功能如何本地化?
- python - Pandas:检查和更改列中的所有项目
- angular - Apache 服务器上的 Angular 应用程序没有重写规则
- python - tensorflow - 会话图为空
- c++ - 如何解决我们必须向前和向后迭代的破碎项链问题