【问题标题】:WebAPI 2 Returns Empty List of ObjectsWebAPI 2 返回空的对象列表
【发布时间】:2023-03-09 01:44:02
【问题描述】:

我有这个应该返回学生列表的操作

[HttpGet("GetAllStudentsByYear/{year}")]
public IActionResult GetAllStudentsByYear(int year)
{
    using (var db = new StudentsCFD())
    {
        List<student> stud = (from std in db.student 
                              join c in db.cppsas 
                                on std.cppsa_id equals c.cppsa_ID 
                              where c.school_yr == year 
                              select std).ToList();
        return Ok(stud);
    }
}

我百分百确定stud不是null,调试时它有28个对象。但是我调用时的输出是这样的。

[
  {}
]

【问题讨论】:

  • 你确定stud中有28个项目吗?暂时把方法改成return Ok(stud.Count());会得到什么?
  • 如果将操作返回类型更改为List&lt;student&gt;return stud;,您会得到相同的结果吗?
  • @DavidG 是的,返回 Ok(stud.Count()) 返回 28
  • @Andrei 我这样做并得到了相同的结果[ { } ],但本质上,实体是一个巨大的对象,我想知道这是否与它们是循环键引用有关?会不会是个问题?
  • 延迟加载的危险 :)

标签: c# asp.net-web-api asp.net-core asp.net-web-api2


【解决方案1】:

可以直接退货吗?如果是,请尝试一次。 例如return stud; 如果返回类型IActionResult给出错误,则使其成为dynamic

【讨论】:

    【解决方案2】:

    在 linq 工作之前添加 db.Configuration.ProxyCreationEnabled = false。它看起来像是对外键的循环或大型引用。

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多