首页 > 解决方案 > 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 参数为空时会引发此错误。

瑞安

标签: c#asp.net-web-apilinq-to-entities

解决方案


尝试使用 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

推荐阅读