【发布时间】:2014-09-02 21:31:41
【问题描述】:
我在使用一个对我来说非常陌生的函数时遇到了问题:
使用 C# MVC 框架 4
我在控制器中调用的存储库类中声明了这个函数:
public IQueryable<Bus> Search(string[] states)
{
// Give all the buses that are inside the list of states that i giving you, no matter upper case or lower case
IQueryable<Bus> query = this.context.Buses;
if (states.Length > 0)
{
query = query.Where(b => states.Select(s => s.ToLower()).ToArray().Contains(b.State.ToLower()));
}
return query;
}
当我使用这个函数执行操作时,我得到了错误:
LINQ to Entities does not recognize the method '**System.String[] ToArray[String]**
...
...
...
但是有一个例外,如果我像这样更改代码(使用 SqlQuery 函数在其他任何东西之前):
public IQueryable<Bus> Search(string[] states)
{
// Give all the buses that are inside the list of states that i giving you, no matter upper case or lower case
IQueryable<Bus> query = this.context.Buses.SqlQuery("SELECT * FROM Buses").AsQueryable();
if (states.Length > 0)
{
query = query.Where(b => states.Select(s => s.ToLower()).ToArray().Contains(b.State.ToLower()));
}
return query;
}
当我执行相同的操作时没有问题。有人知道这是为什么吗?
我知道函数 SqlQuery 返回一个 DbSqlQuery 对象,但之后我将该对象转换为 Queryable 并且出于某种原因这个对象仍然允许我使用 ToArray 函数。
有没有办法在不使用 SqlQuery 函数的情况下做同样的事情?我尝试导入所有这些包(包含在 DbSqlQuery 类声明中,希望声明了扩展但没有):
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
有什么帮助吗?推荐?有什么?
提前致谢。
祝你有美好的一天:)
【问题讨论】:
标签: c# asp.net-mvc-4 linq-to-entities