how apply string.contains method in generic lambda expression

1.5k Views Asked by At


I created a generic lambda expression function like below.
I try to create a dynamic filter query.

public Expression<Func<TSource, bool>> GenericExpression<TSource>(string propertyName, string searchTerm)
    {
        //x=>x.Name.Contains("Emre");
        var parameter = Expression.Parameter(typeof(TSource), "x");
        var property = Expression.Property(parameter,propertyName);
        var search = Expression.Constant(searchTerm,typeof(string));
        MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
        var containsMethodExp = Expression.Call(property, method, search);

        return Expression.Lambda<Func<TSource, bool>>(containsMethodExp, parameter);
    }

I get an error when call GenericExpression function. The error message says that :

Method 'Boolean Contains(System.String)' declared on type 'System.String' cannot be called with instance of type 'System.Int32'

I do not understand error detail.
Could you please explain
Thank you

1

There are 1 best solutions below

0
On

Error fixed. We should check argument type before calling method via PropertyInfo.PropertyType. It works now.

public IQueryable<T> Search<T>(DbSet<T> dbSet, string searchTerm, IGridItem gridItemType) where T : class
    {
        var query = new SearchQuery<T>().Query;
        query = dbSet;
        var gridItemFields = gridItemType.GetType().GetProperties();

        foreach (var field in gridItemFields)
        {
            if (field.PropertyType == typeof(String))
            {
                string _nameProperty = typeof(T).GetProperty(field.Name).Name;
                var lambda = GenericExpression<T>(_nameProperty, searchTerm);
                query = query.Where(lambda);
            }
        }

        return query;
    }

public Expression<Func<TSource, bool>> GenericExpression<TSource>(string propertyName, string searchTerm)
    {
        //x=>x.Name.Contains("Emre");
        ParameterExpression parameter = Expression.Parameter(typeof(TSource), "x");
        Expression property = Expression.Property(parameter,propertyName);
        var search = Expression.Constant(searchTerm,typeof(string));

        MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
        var containsMethodExp = Expression.Call(property, method, search);

        return Expression.Lambda<Func<TSource, bool>>(containsMethodExp, parameter);
    }