Marius Balaban
Marius Balaban

Reputation: 197

Returning DbQuery to view that requires IEnumerable

The problem:

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.Int32]', but this dictionary requires a model item of type 'migros.Models.State'.

What I'm trying to do

I need to pass the result of the following linq query to a View.

using (var db = new migros_mockEntities1())
        {
            var listOfIdeas = (from x in db.States select x.ID); 

            return View(listOfIdeas);
        }

The View requires IEnumerable, but it seems I can't cast the result of the linq query to IEnumerable. I'm using entity framework database first approach.

Upvotes: 0

Views: 4750

Answers (1)

Konstantin Chernov
Konstantin Chernov

Reputation: 1936

The problem is that you trying to return ObjectQuery from within the using block. Try to materialize your object-set

var listOfIdeas = (from x in db.States select x.ID).ToList(); 

Also, dont forget, that dealing with context can be tricky. In your case var listOfIdeas = (from x in db.States select x.ID) is just a query, that will run only when you'd begin to iterate over it. So, if context gets already disposed you'd get an exception, trying to use listOfIdeas.

Upvotes: 1

Related Questions