返回DbQuery来查看需要IEnumerable [英] Returning DbQuery to view that requires IEnumerable
问题描述
问题:
异常详细信息:System.InvalidOperationException:模型项
传递进入字典的类型是
'System.Data.Entity.Infrastructure.DbQuery`1 [System.Int32]',但是这个
字典需要一个类型为migros.Models.State的模型项。
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'.
我想要做什么
我需要将以下linq查询的结果传递给View。
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);
}
视图需要 IEnumerable
,但是似乎我无法将linq查询的结果转换为 IEnumerable
。
我使用实体框架数据库的第一种方法。
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.
推荐答案
问题是您尝试从使用块内返回ObjectQuery。
尝试实现对象集
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();
此外,不要忘了,处理上下文可能很棘手。
在你的情况下 var listOfIdeas =(从db.States中的x选择x.ID)
只是一个查询,只有当你开始迭代它。所以,如果上下文已经被处理,你会得到一个例外,试图使用 listOfIdeas
。
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
.
这篇关于返回DbQuery来查看需要IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!