0
votes

I've been following an ASP .NET MVC tutorial. I've a HomeController with the following Index action.

OdeToFoodDatabase _db = new OdeToFoodDatabase();
public ActionResult Index()
{
    var query = _db.Restaurants.ToList();
    var model = from r in _db.Restaurants
                orderby r.Name ascending
                select r;

    return View(model);
}

my index view is strongly typed with

@model ICollection<OdeToFood.Models.Restaurant>

now this gives the error

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery '1[OdeToFood.Models.Restaurant]', but this dictionary requires a model item of type 'System.Collections.Generic.ICollection '1[OdeToFood.Models.Restaurant]'.......

**this error goes away if I pass model.ToList() instead of model in View() function.
But the tutorial that I'm following passed model in View() function and the code was running. I remember myself that some days ago when i tried that it worked fine. Now why is this so?**

The tutorial in question is here with chapter "Using LINQ"

4
return View(model.ToList());BrendanMcKee
@BrendanMcKee : Please see the edituser3544978

4 Answers

1
votes

just make a small change in the view

@model IEnumerable<OdeToFood.Models.Restaurant>
1
votes

do like this:

@model List<OdeToFood.Models.Restaurant>

and:

var model = (from r in _db.Restaurants
            orderby r.Name ascending
            select r).ToList();

or:

var model = (from r in _db.Restaurants
            orderby r.Name ascending
            select r).ToList<Restaurant>();
0
votes

What you are seeing is an example of delayed execution. Your linq query does not run as soon as you create it, it runs whenever it is needed. In this case model is of type DbQuery. when you pass it into the View it hasn't been run yet.

Calling model.ToList() tells it to execute that query right there and get the data.

As suggested, I believe the code in the view will be an IEnumerable rather than an ICollection. If you look at the DbQuery class you will see

public class DbQuery<TResult> : IOrderedQueryable<TResult>, 
IQueryable<TResult>, IEnumerable<TResult>, IOrderedQueryable, IQueryable, 
IEnumerable, IListSource, IDbAsyncEnumerable<TResult>, IDbAsyncEnumerable

which means that anywhere you can use DbQuery you can use IENumerable

0
votes

Are you mapping your Model to ViewModel correctly? If you are not using Automapper or any kind of mapping framework then use:

OdeToFoodDatabase _db = new OdeToFoodDatabase();
public ActionResult Index()

{
    var query = _db.Restaurants.ToList();
    var model = _db.Restaurants
                 .Take(20)
                 .Select(r => new ResturantViewModel

{  
                      Id=r.Id,
                      Name = r.Name

                   });

    return View(model);
}

In your view use: @model IEnumerable