【问题标题】:LINQ to Entities does not recognize the method 'System.String[] ToArray[String] except when using SqlQuery methodLINQ to Entities 无法识别方法 'System.String[] ToArray[String] ,除非使用 SqlQuery 方法
【发布时间】: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


    【解决方案1】:

    SqlQueryIEnumerable。当你执行它时,数据库就完成了。之后,您调用.AsQueryable(它会尝试给您一个 Queryable,但如果不能,它会给您一个看起来像 IQueryable 的 IEnumerable)。 .ToArray 发生在客户端而不是服务器端的内存中。

    【讨论】:

    • 谢谢,很清楚我会寻找更好的方法来管理这个并上传解决方案。
    【解决方案2】:

    我找到的解决方案很简单,我只是使用 ToArray 函数 before 像这样的 where 语句:

    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)
        {
            states = states.Select(s => s.ToLower()).ToArray();
            query = query.Where(b => states.Contains(b.State.ToLower()));
        }
    return query;
    }
    

    感谢 insta 的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-03
      • 2013-04-07
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      相关资源
      最近更新 更多