ASP.Net MVC Web API返回对象列表

Mar*_*ark 1 asp.net asp.net-mvc asp.net-web-api

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)

它目前显示错误:

无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'MvcApplication4.Models.CarTypes'.存在显式转换(您是否错过了演员?)

如果我在查询中使用Select/SelectMany/Where,这有关系吗?

Wes*_*olf 8

首先你需要用Where而不是Select; 其次,在将其更改为Where之后不需要使用AsEnumerable(),但您可能必须调用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;
    }
Run Code Online (Sandbox Code Playgroud)

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