c# - web api函数抛出System.InvalidOperationException异常
问题描述
我从移动设备和 Rest 客户端在我的 api 中调用以下代码:
[HttpGet]
[Route("api/mobile/GetUsersList")]
public IHttpActionResult GetUsersList()
{
var users = from c in db.Users
select new { c.id, c.user_name, c.reports_to };
return Ok(users.ToList());
}
我收到以下错误:
转换为值类型“System.Int32”失败,因为具体化值为 null。结果类型的泛型参数或查询必须使用可为空的类型
我没有使用 where 所以我不确定为什么这个简单的查询会抛出这个错误。
我正在使用 Advanced Rest Client 测试此功能的 Http GET。
我在其他 SO 帖子中看到,当 where 参数为空时会引发此错误。
瑞安
解决方案
尝试使用 cast 直接指定名称
var users = from c in db.Users
select new { id= (int?)c.id, user_name = c.user_name, reports_to = c.reports_to };
或者
id = c.id ?? 0
推荐阅读
- c# - 在 Entity Framework Core 中使用具有多对多关系的列表
- c# - 绕过带标签的语句
- powershell - 有没有办法为 Windows 剪贴板编写粘贴后挂钩?
- python - 使用正则表达式或其他任何方法使用 python 解析 CSS?
- python - 在 Jupyter 中找不到文件
- java - onActivityResult 在不同的片段上
- javascript - 为什么 event.target 中的值不等于 event.target.value
- javascript - 使用 css 和/或 SASS 的 DIV 中的动态垂直条纹
- ios - 如何在 swift 中使用 TextField 作为 searchBar?
- c# - 如何在经典 Xamarin 解决方案中正确使用 WCF Web 服务?