代码之家  ›  专栏  ›  技术社区  ›  Steven Evers

where子句中的扩展方法

  •  2
  • Steven Evers  · 技术社区  · 15 年前

    我在字符串类型上创建了一个简单的扩展方法:

    public static bool Contains(this string word, string[] values)
    {
        foreach(string s in values)
        {
            if(!word.Contains(s))
                return false;
        }
    
        return true;
    }
    

    现在,我有一个linq查询,看起来像这样:

    public static IEnumerable<ISearchable> Search(params string[] keywords)
    {
        XPQuery<Customer> customers = new XPQuery<Customer>(unitOfWork); // **
        var found = from c in customers
                    where c.Notes.Contains(keywords)
                    select c;
    
        return found.Cast<ISearchable>();
    }
    

    我在where子句上得到一个“method not supported”异常,如果使用字符串。包含方法。

    **XPQuery是一个devexpress组件,因为我使用的ORM是linq到xpo的查询对象。

    4 回复  |  直到 15 年前
        1
  •  2
  •   Community Mohan Dere    8 年前

    这里是实体框架的解决方法,也许你可以试试。 'Contains()' workaround using Linq to Entities?

        2
  •  2
  •   Mark Byers    15 年前

    您的代码是合法的C#但是您使用的框架可能不支持它。你可以试试这个:

    where keywords.All(keyword => c.Notes.Contains(keyword))
    

    ContainsAll ContainsAny .

        3
  •  1
  •   Massimiliano    15 年前

    一般来说,要么需要重写查询以摆脱自定义方法(请参见Mark的回答),要么可以拆分查询以获取一些初步数据,然后使用LINQ to Objects,用方法选择所需的集。前者通常表现得更好。

        4
  •  0
  •   Tomas Petricek    15 年前

    我不知道 XPQuery ,但我假设它使用表达式树并将其转换为其他语言(例如,像linqtosql这样的语言,它生成SQL)。问题是库不知道您的扩展方法。它不知道应该生成什么相应的代码(在目标语言中)来代替您的方法。