我知道.Contains()方法确实喜欢LIKE %therm%,.StartsWith()方法确实喜欢LIKE therm%和.EndsWith()方法一样LIKE %therm但是......
有没有办法在下面做**Linq to Entities**?
SELECT * FROM [dbo].[Users] WHERE Name LIKE 'rodrigo%otavio%diniz%waltenberg'
Run Code Online (Sandbox Code Playgroud)
PS:我正在使用LINQ to ENTITIES.不是LINQ TO SQL
在linq to Entities中,我们需要一个类似"sql like"的方法.我们已经为IQueryable实现了我们自己的扩展方法,因为包含的方法对我们不起作用,因为它不接受像'%a%b%'这样的模式
创建的代码是:
private const char WildcardCharacter = '%';
public static IQueryable<TSource> WhereLike<TSource>(this IQueryable<TSource> _source, Expression<Func<TSource, string>> _valueSelector, string _textSearch)
{
if (_valueSelector == null)
{
throw new ArgumentNullException("valueSelector");
}
return _source.Where(BuildLikeExpressionWithWildcards(_valueSelector, _textSearch));
}
private static Expression<Func<TSource, bool>> BuildLikeExpressionWithWildcards<TSource>(Expression<Func<TSource, string>> _valueSelector, string _textToSearch)
{
var method = GetPatIndexMethod();
var body = Expression.Call(method, Expression.Constant(WildcardCharacter + _textToSearch + WildcardCharacter), _valueSelector.Body);
var parameter = _valueSelector.Parameters.Single();
UnaryExpression expressionConvert = Expression.Convert(Expression.Constant(0), typeof(int?));
return Expression.Lambda<Func<TSource, bool>> (Expression.GreaterThan(body, expressionConvert), parameter);
}
private static MethodInfo GetPatIndexMethod() …Run Code Online (Sandbox Code Playgroud) 如何使用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)
但即使搜索肯定在数据库中的查询字符串,它也不会返回任何结果.我究竟做错了什么?