无法隐式转换类型';System.Linq.IQueryable<>';到';System.L
本文关键字:System lt IQueryable gt Linq 类型 转换 | 更新日期: 2023-09-27 17:51:07
可能重复:
LINQ2SQL:无法转换IQueryable<gt;到IOrderedQueryable错误
我在控制器的searchString中出现了这个错误。。
这是我的代码:
if (!String.IsNullOrEmpty(searchString))
{
posts = posts.Where(post => post.Body == searchString);
}
我在索引中使用这些代码进行搜索。我是不是在这里申报了什么问题?我已经试过在谷歌上搜索了,但没有找到明确的答案。提前感谢任何能帮助我的人。
最可能的原因是在具有OrderBy
的查询中为posts
使用了隐式var
声明。如果你把它换成
IQueryable<Post> posts = someSource.Where(cond).OrderBy(/*the culprit*/);
这个错误应该会消失。
您的posts
变量的类型似乎是IOrderedQueryable<Post>
,但您正在为它分配一个IQueryable<Post>
。我看到了两种方法来解决这个问题,要么将变量类型修改为IQueryable<Post>
,要么像这样对查询进行排序:
posts = posts.Where(post => post.Body == searchString)
.OrderBy(post => post.Date);
posts
是IOrderedQueryable
,对where的调用返回IQueryable
。为什么不显式地声明变量,看看它是否解决了问题。