实体框架中的"喜欢"查询

ssl*_*ian 3 entity-framework wildcard

如何使用edo实体框架在ASP.net MVC中获取通配符文本搜索(如SQL的"like"语句)?

我以为这会起作用:

var elig = (from e in _documentDataModel.Protocol_Eligibility_View
            where e.criteria.Contains(query)
            select e);
Run Code Online (Sandbox Code Playgroud)

但即使搜索肯定在数据库中的查询字符串,它也不会返回任何结果.我究竟做错了什么?

Pav*_*lev 8

2019年更新

对于实体框架 6.2,您可以使用DBFunctions

例如:

try
{
    using (var db = new YOUREntities())
    {
        var data = db.LenderProgram.Where(i => DbFunctions.Like(i.LenderProgramCode, "OTO%"))
            .ToList();
        return data;
    }
}
catch (Exception e)
{
    e.HandleException();
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ter 7

这个人为Linq做了一个非常好的"WhereLike"扩展,它接受任何通配符并将两个值(其中一个来自表达式)与从通配符的位置派生的泛型方法进行比较.

  • x% - >从头开始
  • %x - > endswith
  • %x% - >包含

http://trentacular.com/2010/08/linq-to-entities-wild-card-like-extension-method/

编辑:文章似乎失败了.我将粘贴下面的扩展代码:

public static class LinqHelper
    {
        //Support IQueryable (Linq to Entities)
        public static IQueryable<TSource> WhereLike<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, string>> valueSelector, string value, char wildcard)
        {
            return source.Where(BuildLikeExpression(valueSelector, value, wildcard));
        }

        //Support IEnumerable (Linq to objects)
        public static IEnumerable<TSource> WhereLike<TSource>(this IEnumerable<TSource> sequence, Func<TSource, string> expression, string value, char wildcard)
        {
            var regEx = WildcardToRegex(value, wildcard);

            //Prevent multiple enumeration:
            var arraySequence = sequence as TSource[] ?? sequence.ToArray();

            try
            {
                return arraySequence.Where(item => Regex.IsMatch(expression(item), regEx));
            }
            catch (ArgumentNullException)
            {
                return arraySequence;
            }
        }

        //Used for the IEnumerable support
        private static string WildcardToRegex(string value, char wildcard)
        {
            return "(?i:^" + Regex.Escape(value).Replace("\\" + wildcard, "." + wildcard) + "$)";
        }

        //Used for the IQueryable support
        private static Expression<Func<TElement, bool>> BuildLikeExpression<TElement>(Expression<Func<TElement, string>> valueSelector, string value, char wildcard)
        {
            if (valueSelector == null) throw new ArgumentNullException("valueSelector");

            var method = GetLikeMethod(value, wildcard);

            value = value.Trim(wildcard);
            var body = Expression.Call(valueSelector.Body, method, Expression.Constant(value));

            var parameter = valueSelector.Parameters.Single();
            return Expression.Lambda<Func<TElement, bool>>(body, parameter);
        }

        private static MethodInfo GetLikeMethod(string value, char wildcard)
        {
            var methodName = "Equals";

            var textLength = value.Length;
            value = value.TrimEnd(wildcard);
            if (textLength > value.Length)
            {
                methodName = "StartsWith";
                textLength = value.Length;
            }

            value = value.TrimStart(wildcard);
            if (textLength > value.Length)
            {
                methodName = (methodName == "StartsWith") ? "Contains" : "EndsWith";
            }

            var stringType = typeof(string);
            return stringType.GetMethod(methodName, new[] { stringType });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,答案中提供的这个链接已经失效。感谢您提供代码。 (2认同)

Ree*_*sey 5

String.Contains应该正常工作.SQL的LIKE语句通常通过String.StartsWith,String.Contains或String.EndsWith处理.

但是,你可能遇到套管问题.你可以尝试:

var elig = (from e in _documentDataModel.Protocol_Eligibility_View
        where e.criteria.ToLower().Contains(query.ToLower())
        select e);
Run Code Online (Sandbox Code Playgroud)


Ech*_*lon 5

Linq to实体不支持SqlMethods方法,但是可以使用字符串函数代替:

.Where(entity => entity.Name.Contains("xyz"))

.Where(entity => entity.Name.EndsWith("xyz"))

.Where(entity => entity.Name.StartsWith("xyz"))
Run Code Online (Sandbox Code Playgroud)