[英]Converting a Linq expression tree that relies on SqlMethods.Like() for use with the Entity Framework
我最近从使用Linq到Sql切换到了实体框架。 我一直在苦苦挣扎的事情之一就是获得通用的IQueryable扩展方法,该方法是为Linq to Sql与实体框架一起使用而构建的。 此扩展方法依赖于SqlMethods的Like()方法,Linq特定于Sql。 我真正喜欢这种扩展方法的地方在于,它允许我在运行时在任何对象上动态构造Sql Like语句,只需简单地传入属性名称(作为字符串)和查询子句(也作为字符串)即可。 这种扩展方法对于使用诸如flexigrid或jqgrid之类的网格非常方便。 这是Linq to Sql版本(摘自本教程: http : //www.codeproject.com/KB/aspnet/MVCFlexigrid.aspx ):
public static IQueryable<T> Like<T>(this IQueryable<T> source,
string propertyName, string keyword)
{
var type = typeof(T);
var property = type.GetProperty(propertyName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constant = Expression.Constant("%" + keyword + "%");
var like = typeof(SqlMethods).GetMethod("Like",
new Type[] { typeof(string), typeof(string) });
MethodCallExpression methodExp =
Expression.Call(null, like, propertyAccess, constant);
Expression<Func<T, bool>> lambda =
Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
使用这种扩展方法,我可以简单地执行以下操作:
someList.Like(“ FirstName”,“ mike”);
要么
anotherList.Like(“ ProductName”,“ widget”);
是否有使用Entity Framework的等效方法?
提前致谢。
SQL方法PATINDEX提供与LIKE相同的功能。 因此,可以使用SqlFunctions.PatIndex方法。
.Where(x => SqlFunctions.PatIndex("%123%ABC", x.MySearchField) > 0)
要么
var miSqlPatIndex = typeof(SqlFunctions).GetMethod(
"PatIndex",
BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
null,
new Type[] { typeof(string), typeof(string) },
null);
expr = Expression.GreaterThan(
Expression.Call(
miSqlPatIndex,
new Expression[] { Expression.Constant("%123%ABC"), MySearchField }),
Expression.Convert(Expression.Constant(0), typeof(int?)));
我可以在这里找到一个好的解决方案: http : //www.codeproject.com/KB/aspnet/AspNetMVCandJqGrid.aspx
它本质上使用字符串类的“包含”方法,而不是SqlMethods类的Like方法。
表达式条件= Expression.Call(memberAccess,typeof(string).GetMethod(“ Contains”),Expression.Constant(keyword));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.