1

渡されたTyreIDがCarTypeクラスの主キーではない「CarTypes」オブジェクトのリストを(2番目のメソッドから)正しく返すにはどうすればよいですか?たとえば、すべてのCarTypeのリストを返したいと思います、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;
}

現在、エラーが表示されています。

タイプ「System.Collections.Generic.IEnumerable」を「MvcApplication4.Models.CarTypes」に暗黙的に変換することはできません。明示的な変換が存在します(キャストがありませんか?)

また、クエリでSelect / SelectMany / Whereを使用するかどうかは重要ですか?

4

3 に答える 3

9

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.

于 2012-06-08T10:31:14.417 に答える
1

「選択」の代わりに「場所」を使用する必要があります。

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 :)

于 2012-06-08T10:08:57.850 に答える
1

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...

于 2012-06-08T10:28:01.320 に答える