Converting a Linq expression tree that relies on SqlMethods.Like() for use with the Entity Framework

Posted by JohnnyO on Stack Overflow See other posts from Stack Overflow or by JohnnyO
Published on 2010-04-01T05:10:27Z Indexed on 2010/04/01 5:13 UTC
Read the original article Hit count: 380

Filed under:
|
|
|
|

I recently switched from using Linq to Sql to the Entity Framework. One of the things that I've been really struggling with is getting a general purpose IQueryable extension method that was built for Linq to Sql to work with the Entity Framework. This extension method has a dependency on the Like() method of SqlMethods, which is Linq to Sql specific. What I really like about this extension method is that it allows me to dynamically construct a Sql Like statement on any object at runtime, by simply passing in a property name (as string) and a query clause (also as string). Such an extension method is very convenient for using grids like flexigrid or jqgrid. Here is the Linq to Sql version (taken from this tutorial: 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);
    }

With this extension method, I can simply do the following:

someList.Like("FirstName", "mike");

or

anotherList.Like("ProductName", "widget");

Is there an equivalent way to do this with Entity Framework?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about LINQ