Mark
Mark

Reputation: 7818

ASP.Net MVC Web API Return list of objects

How do I correctly return a list of "CarTypes" objects (from the second method), where the TyreID that is passed in, is not the primary key of the CarType class - so for example, I want to return a list of all CarTypes, where the TyreID is 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;
}

It currently shows the error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'MvcApplication4.Models.CarTypes'. An explicit conversion exists (are you missing a cast?)

And does it matter if I use Select/SelectMany/Where in the query?

Upvotes: 1

Views: 34171

Answers (3)

WestDiscGolf
WestDiscGolf

Reputation: 4108

Firstly you need to use Where instead of Select; secondly you don't need to use AsEnumerable() after you've changed it to Where but you might have to call ToList() so that the Linq2Sql/EntityFramework executes the query before returning the values to the view.

 // 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;
    }

I've also added in an additional check after the query has executed but you might not need this depending on how you want to handle an empty collection.

Upvotes: 9

user1429080
user1429080

Reputation: 9166

Shouldn't you have:

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

Instead of:

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

Note: I would have made this a comment under PanJanek's answer but I'm not currenlty allowed beacuse of my low reputation...

Upvotes: 1

PanJanek
PanJanek

Reputation: 6685

You should use "Where" Instead of "Select".

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

"Select" is for specifying which data should be returned for each record, not for filtering the records. Your query with "Select" returns boolean values: false for records with TyreID != id and true for one record where TyreID = id :)

Upvotes: 1

Related Questions