c# - 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);
}
一个星期以来,我一直在努力解决这个问题。任何帮助将不胜感激,在此先感谢您。
解决方案
我通过执行以下操作设法解决了这个问题。.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));
推荐阅读
- powerbi - 基于power bi dax中两列的过滤措施
- hibernate - 从休眠 4.3.11.Final 升级到 5.4.3.Final 后如何解决 MappingExceptions?
- sql-server - 您如何调试或单步调试 SQL Server Management Studio 18 中的代码?
- python-3.x - 如何插入新数据进行预测?学习
- django - DEBUG为False时获取更新查询,不影响代码执行
- java - 创建和导入自定义 Spring 库,同时分离共享依赖项
- java - 是否可以在没有调度程序的情况下使用 Apache Airflow 进行编排任务?
- python - Python:动态定义类的函数
- java - 异步 Java:如何组织必须按顺序完成的嵌套订阅?
- php - 如何在不修改会话到期的情况下延长购物车寿命?