简体   繁体   中英

How to call SqlFunctions.PatIndex() with Expressions?

I have a business layer call that works like so:

CustomerRepository.Get(c => SqlFunctions.PatIndex("%" + arg + "%", c.FirstName));

I am trying to build this using expressions:

    public virtual IEnumerable<TEntity> Like(string LikeString, string Target)
    {
        MethodInfo method = typeof(SqlFunctions).GetMethod("PatIndex");
        var arg1 = Expression.Constant(LikeString);
        var item = Expression.Parameter(typeof(TEntity), "item");
        var prop = Expression.Property(item, Target);

        MethodCallExpression resultExp =
            Expression.Call(method, arg1, prop);

        var value = Expression.Constant(0, typeof(int?));

        var greaterThan = Expression.GreaterThan(resultExp, value);

        var lambda = Expression.Lambda<Func<TEntity, bool>>(greaterThan, item);

        var result = Repo<TEntity>.Get().AsQueryable().Where(lambda);

        return result;
    }

When I call the above method, I get the following exception:

This function can only be invoked from LINQ to Entities.

Any ideas of how to get past this or do what I want it to do? Does my Expression code look ok?

Figured out the issue

from:

var result = Repo<TEntity>.Get().AsQueryable().Where(lambda);

to:

var result = Repo<TEntity>.Get(lambda);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM