首页 > 解决方案 > Dotnet Core Web API 返回空列表 | 延迟加载不起作用

问题描述

我的 API 中有一个端点,它返回所选项目的所有数据。该项目是一个名为的根对象Survey,它有一个页面列表。

public partial class Surveys
{
    public Surveys()
    {
        Pages = new HashSet<Pages>();
    }

    public string Description { get; set; }
    public string Name { get; set; }
    public long Syear { get; set; }
    public long Quarter { get; set; }
    public ICollection<Pages> Pages { get; set; }
}

Pages看起来像这样的模型类。

public partial class Pages
{
    public Pages()
    {
        Elements = new HashSet<Elements>();
    }

    public string Id { get; set; }
    public long Number { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? PageFlowId { get; set; }
    public bool NamedPage { get; set; }
    public bool? IsFirst { get; set; }
    public bool? IsLast { get; set; }
    public long? SurveyQuarter { get; set; }
    public long? SurveySyear { get; set; }

    public PagesFlows PageFlow { get; set; }
    public Surveys Survey { get; set; }
    public ICollection<Elements> Elements { get; set; }
}

但是当我发送 GET 请求时返回一个空列表Pages

[
    {
        "description": "Customer Satisfaction Survey",
        "name": "Customer Survey",
        "syear": 2019,
        "quarter": 1,
        "pages": []
    }
]

数据库包含数据。表的主键是复合键(Syear、Quarter)。我的 API 看起来像这样。

public async Task<IActionResult> GetSurveys([FromRoute]long syear, long quarter)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var surveys = await _context.Surveys.Include(s => s.Pages).SingleOrDefaultAsync(s => s.Syear == syear && s.Quarter == quarter);
        if (surveys == null)
        {
            return NotFound();
        }

        return Ok(surveys);
    }

一个星期以来,我一直在努力解决这个问题。任何帮助将不胜感激,在此先感谢您。

标签: c#.net-coreentity-framework-coreasp.net-core-webapi

解决方案


我通过执行以下操作设法解决了这个问题。.Include(s => s.Pages)从这里删除,

var surveys = await _context.Surveys.Include(s => s.Pages).SingleOrDefaultAsync(s => s.Syear == syear && s.Quarter == quarter);

我已经virtual为所有引用的类添加了关键字。

public partial class Pages
{
    public Pages()
    {
        Elements = new HashSet<Elements>();
    }

    public string Id { get; set; }
    public long Number { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? PageFlowId { get; set; }
    public bool NamedPage { get; set; }
    public bool? IsFirst { get; set; }
    public bool? IsLast { get; set; }
    public long? SurveyQuarter { get; set; }
    public long? SurveySyear { get; set; }

    public virtual PagesFlows PageFlow { get; set; }
    public virtual Surveys Survey { get; set; }
    public virtual ICollection<Elements> Elements { get; set; }
} 

然后我按照这里Microsoft.EntityFrameworkCore.Proxies的描述从 NuGet 安装了包

Sturtup.cs并在ConfigureServices方法中启用了延迟加载代理。

services.AddDbContext<MyDBContext>
                (options => options.UseLazyLoadingProxies().UseSqlServer(connection));

推荐阅读