【发布时间】:2010-04-01 05:10:27
【问题描述】:
我最近从使用 Linq 切换到 Sql 到 Entity Framework。我一直在努力解决的一件事是获得一个通用的 IQueryable 扩展方法,该方法是为 Linq to Sql 构建的,可以与实体框架一起使用。此扩展方法依赖于 SqlMethods 的 Like() 方法,该方法是 Linq to 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");
实体框架有没有等效的方法?
提前致谢。
【问题讨论】:
标签: c# linq linq-to-sql entity-framework linq-to-entities