Dolaps
Dolaps

Reputation: 279

EF code first cannot convert type to int

I am creating a function on my restaurant review website that gets the cuisine of the last review and then finds other reviews with same cuisine that have a higher average score. It then saves every restaurant id in a database. However I keep on receiving the error Cannot implicitly convert type 'System.Linq.IQueryable<int>' to 'int' on the line where r.id = samecuisine.

Any help would be grateful.

var samecuisine = (from r in db.Reviews
                   where r.Cuisine == review.Cuisine
                   select r.id);

var pick = (from r in db.Reviews
            where r.id = samecuisine
            select r.score).Average();

var choices = (from r in db.Reviews
               where r.score >= pick
               select r.RestaurantId).ToList();

Upvotes: 1

Views: 155

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503310

It's unclear why you'd want to get a review ID at all. You're only interested in the scores for those reviews, right? I suspect you actually want to take part of your first query and part of your second:

var averageScoreForCuisine = (from r in db.Reviews
                              where r.Cuisine == review.Cuisine
                              select r.score).Average();

Or to my mind more readably:

var averageScoreForCuisine = db.Reviews
                               .Where(r => r.Cuisine == review.Cuisine)
                               .Average(r => r.score);

Upvotes: 4

Maarten
Maarten

Reputation: 22955

Your query

var samecuisine = (from r in db.Reviews
                   where r.Cuisine == review.Cuisine
                   select r.id);

returns an IQueryable<int>, not an actual int.

Try to retrieve the .FirstOrDefault(), this yields the first result (or the default value 0).

Upvotes: 1

Related Questions