【问题标题】:ASP.Net MVC Web API Return list of objectsASP.Net MVC Web API 返回对象列表
【发布时间】:2012-06-08 10:04:06
【问题描述】:

如何正确返回“CarTypes”对象列表(来自第二种方法),其中传入的 TyreID 不是 CarType 类的主键 - 例如,我想返回一个列表在 TyreID 为 5 的所有 CarType 中:

// GET api/CarTypes
public IEnumerable<CarTypes> GetCarTypes()
{
    return db.CarTypes.AsEnumerable();  //This works fineCar
}

// GET api/CarTypes/5
public IEnumerable<CarTypes> GetCarTypes(long id)
{
    CarTypes cartypes = db.CarTypes.Select(t => t.TyreID == id).AsEnumerable();
    if (roomtypes == null)
    {
        throw new HttpResponseException(Request
            .CreateResponse(HttpStatusCode.NotFound));
    }

    return cartypes;
}

目前显示错误:

无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“MvcApplication4.Models.CarTypes”。存在显式转换(您是否缺少演员表?)

如果我在查询中使用 Select/SelectMany/Where 是否重要?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-web-api


    【解决方案1】:

    首先你需要使用Where而不是Select;其次,在将 AsEnumerable() 更改为 Where 之后,您不需要使用它,但您可能必须调用 ToList() 以便 Linq2Sql/EntityFramework 在将值返回到视图之前执行查询。

     // GET api/CarTypes/5
        public IEnumerable<CarTypes> GetCarTypes(long id)
        {
            var cartypes = db.CarTypes.Where(t => t.TyreID == id).ToList();
            if (cartypes == null || !cartypes.Any())
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
    
            return cartypes;
        }
    

    我还在查询执行后添加了额外的检查,但您可能不需要此检查,具体取决于您要如何处理空集合。

    【讨论】:

    • 嗨@WestDiscGolf - VS(2012 RC)在 db.CarTypes 上显示错误...无法将类型“System.Collections.Generic.List”隐式转换为“ MvcApplication4.Models.cartypes
    • 嗨@WestDiscGolf,评论可能太论坛了,但是对上述实现有疑问,如果您查看API,它返回一个列表,但我们将IEnumerable作为返回类型方法。上面的实现会成功..毫无疑问。我的问题是,1)可以互换使用两者是否可以 2)当然,我们正在返回一个列表,那么返回类型为 List 而不是 IEnumerable 有什么危害
    • 嗨@TechQuery,所以它不是那么“可互换”,而是 List 实现 IEnumerable (msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx) 的事实,但很多事情也是如此。如果你返回一个接口,那么任何实现它的东西都可以用来消费它,但是如果使用更具体的实现,例如 List,那么它会限制可以消费的东西。
    • 这很有趣,但您的“cartypes”永远不会为空。它始终是一个包含零个或多个元素的列表。
    【解决方案2】:

    你应该使用“Where”而不是“Select”。

    CarTypes cartypes = db.CarTypes.Where(t => t.TyreID == id).AsEnumerable();
    

    “选择”用于指定每条记录应返回哪些数据,而不是用于过滤记录。您的“选择”查询返回布尔值:对于 TyreID != id 的记录为 false ,对于 TyreID = id 的记录为 true :)

    【讨论】:

    • 另外,你不想返回 cartypes.AsEnumerable()
    • 嗨 - 我在 Linq 语句的末尾确实有 .AsEnumerable() - 但无论我是否添加 cartypes.AsEnumerable() ,错误仍然存​​在于 linq 语句中。再次感谢,马克。
    【解决方案3】:

    你不应该有:

    IEnumerable<CarTypes> cartypes = db.CarTypes.Where(t => t.TyreID == id).AsEnumerable();
    

    代替:

    CarTypes cartypes = db.CarTypes.Select(t => t.TyreID == id).AsEnumerable();
    

    注意:我会在 PanJanek 的回答下发表评论,但由于我的声誉低下,我目前不被允许...

    【讨论】:

    • 非常感谢 - 这就是我所缺少的(IEnumerable 在行首) - PanJanek/Mike - 也感谢你的帮助 - 干杯,马克
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多