Returning DbQuery to view that requires IEnumerable

与世无争的帅哥 提交于 2019-12-13 06:07:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/11879870/returning-dbquery-to-view-that-requires-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!