【问题标题】:Eager Loading using Include does not show all records but one使用 Include 的 Eager Loading 不显示所有记录,只显示一个
【发布时间】:2019-11-26 05:49:57
【问题描述】:

我在我的 WebAPI 项目中使用 EF Core 和 DB 优先方法。

我有以下为 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 有语法错误?

【问题讨论】:

  • 看起来 EF 获取了所有数据,但 JSON 在某处被截断。也许用 PostMan 或 Fiddler 运行 API?
  • 您的“浏览器结果”是什么?那是在 HTML 源代码中输出的内容,您在控制台窗口中看到的内容,是什么?查看您的实际 JS 代码可能也会有所帮助。
  • 您应该将您的实体映射到 DTO。这解决了你的问题。
  • this 相关吗?
  • @GertArnold - 是的!谢谢!

标签: entity-framework asp.net-core entity-framework-core asp.net-core-webapi


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多