entity-framework - 使用 Include 的 Eager Loading 不显示所有记录,只显示一个
问题描述
我在我的 WebAPI 项目中使用 EF Core 和 DB first 方法。
我有以下为 StoreLocation 自动生成的模型类:
public partial class StoreLocation
{
public StoreLocation()
{
Sales = new HashSet<Sales>();
}
public int Id { get; set; }
public string LocationName { get; set; }
public string Description { get; set; }
public int? NumberOfStaff { get; set; }
public ICollection<Sales> Sales { get; set; }
}
还有一个销售类:
public partial class Sales
{
public int Id { get; set; }
public decimal? SalesPrice { get; set; }
public string ProductType { get; set; }
public int? StoreLocation { get; set; }
}
然后我有一个方法来获取一个基于 id 的 StoreLocation 及其所有销售额,如下所示:
[HttpGet("StoreWithSales/{id}")]
public async Task<ActionResult<IEnumerable<StoreLocation>>> GetStoreWithSales(int id)
{
return await _context.StoreLocation.Where(s => s.Id == id).Include(store => store.Sales).ToListAsync();
}
我通过使用 Include() 来使用急切加载。我的问题是,当我运行 api 并触发这个调用时,我只得到第一个没有结尾“]”的项目
在此处查看我在浏览器中的结果:
[{"id":1,"locationName":"Copenhagen","description":"Assimilated multi-tasking secured line","numberOfStaff":2,"sales":[{"id":2,"salesPrice":47.80,"productType":"Socks","storeLocation":1
其余的都不见了,为什么以及在哪里?当我尝试调试时,我可以看到所有销售记录实际上都已加载但未在浏览器中返回。感谢您的任何提示!
编辑:
当我尝试在 Postman 中发出这个特殊的电话时,我得到:Could not get any response
.
在我测试的浏览器中https://localhost:XXXXX/api/sales/storeWithSales/2
,有时会显示我在上面发布的内容,有时浏览器页面是空白的。在控制台中出现以下错误:Failed to load resource: net::ERR_SPDY_PROTOCOL_ERROR
其他 GET 调用,我只需从表中检索所有值都没有问题,并且不存在来自控制台的上述错误。我在 Chrome 和 IE 11 中尝试过
编辑 2:在 Firefox 中,我得到了这个:SyntaxError: JSON.parse: end of data after property value in object at line 1 column 173 of the JSON data API response
所以看起来服务器生成 json 时有语法错误?
解决方案
似乎 JSON 被截断了,尝试忽略下面的引用循环
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
}
推荐阅读
- uwp - 如何导航到 UWP 页面的实例?
- perl - 为什么官方的 perl docker 镜像有两个版本的 perl?
- reactjs - 带有钩子的 React 函数组件计数器
- laravel - 使用表单中的选择后从数据库请求数据
- react-native - React Native 导航到另一个页面
- python - 提高 pyautogui.press 的速度
- php - 使用 Laravel 5.8 可邮寄的多种表单验证
- java - 流屏幕使用 MediaRecorder 做出原生反应
- bash - 如何在没有包管理器的情况下在 Mac OSX Mojave 上正确安装 ImageMagick
- reactjs - 如何在 manifest.json 中使用数据库值