首页 > 解决方案 > 使用 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 时有语法错误?

标签: entity-frameworkasp.net-coreentity-framework-coreasp.net-core-webapi

解决方案


似乎 JSON 被截断了,尝试忽略下面的引用循环

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );
}

参考https://github.com/dotnet/core/issues/1240


推荐阅读