有没有写LINQ到实体的自定义函数的简单方法? [英] Is there a simple way to write a custom function in LINQ to Entities?

查看:246
本文介绍了有没有写LINQ到实体的自定义函数的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写我的实体框架应用程序的简单搜索查询。我需要检查是否一堆字段为空,如果没有,他们调用ToLower将(),并比较搜索查询。 LINQ查询看起来是这样的:

I'm writing a simple search query for my Entity Framework application. I need to check if a bunch of fields are null, and if not, call ToLower() on them and compare to the search query. The LINQ query looks something like this:

public IQueryable<Store> SearchStores(string q, IQueryable<Store> source)
{
    q = q.ToLower();

    return (
        from s in source
        where (
            (s.Name != null && s.Name.ToLower().Contains(q)) ||
            (s.Description != null && s.Description.ToLower().Contains(q)) ||
            ...
}

有很多像这样的线路,所以我很想写一个辅助方法,清理了一下:

There are a lot of lines like this, so I was tempted to write a helper method to clean it up a bit:

public static bool SafeSearch(this string s, string q)
{
    return s == null ? false : s.ToLower().Contains(q);
}

这的当然不行,不过,因为LINQ到实体不理解安全搜索功能是什么:

This of course doesn't work, though, since LINQ to entities doesn't understand what the SafeSearch function is:

LINQ到实体无法识别该方法'布尔安全搜索(System.String,System.String)的方法,而这种方法不能被翻译成店的表情。

LINQ to Entities does not recognize the method 'Boolean SafeSearch(System.String, System.String)' method, and this method cannot be translated into a store expression.

有没有一种简单的方法来写这样一个简单的自定义功能?

Is there an easy way to write a simple custom function like this?

谢谢!

推荐答案

由于LINQ使用未执行,直到你实际调用数据库,你需要换一个谓词里面的函数表达式。

Since linq uses expression that are not executed until you actually calling the database, you would need to wrap your function inside of a predicate.

private static Func<Country, bool> Predicate(string q)
{
    return x => (
        q.SafeSearch(x.Name) ||
        q.SafeSearch(x.Description)
        );
}



此外,通过调用它的查询扭转安全搜索扩展方法,会照顾情况下,x.Name为null。

Also reversing the SafeSearch extension method by calling it on query, will take care of cases where x.Name is null.

public static class SearchExt
{
    public static bool SafeSearch(this string q, string param)
    {
        return param == null ? false : param.ToLower().Contains(q);
    }
}



,然后你可以用extesion方法使用它

and then you could use it with extesion methods

return source.Where(Predicate(q));

或使用LINQ表达

return from p in source
       where Predicate(q).Invoke(p)
       select p;

这篇关于有没有写LINQ到实体的自定义函数的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆