Hi, I'm using the Entity Framework and I developed this extension method:
public static IQueryable<TResult> Like<TResult>(this IQueryable<TResult> query, Expression<Func<TResult, string>> field, string value)
{
var expression = Expression.Lambda<Func<TResult, bool>>(
Expression.Call(field.Body, typeof(string).GetMethod("Contains"),
Expression.Constant(value)), field.Parameters);
return query.Where(expression);
}
this code work correctly if I use it like this:
var result = from e in context.es.Like(r => r.Field, "xxx")
select e
Now I need to call this extension method programmatically:
public static IQueryable<TSource> SearchInText<TSource>(this IQueryable<TSource> source, string textToFind)
{
// Collect fields
PropertyInfo[] propertiesInfo = source.ElementType.GetProperties();
List<string> fields = new List<string>();
foreach (PropertyInfo propertyInfo in propertiesInfo)
{
if (
(propertyInfo.PropertyType == typeof(string)) ||
(propertyInfo.PropertyType == typeof(int)) ||
(propertyInfo.PropertyType == typeof(long)) ||
(propertyInfo.PropertyType == typeof(byte)) ||
(propertyInfo.PropertyType == typeof(short))
)
{
fields.Add(propertyInfo.Name);
}
}
ParameterExpression parameter = Expression.Parameter(typeof(TSource), source.ElementType.Name);
Expression expression = Expression.Lambda(Expression.Property(parameter, typeof(TSource).GetProperty(fields[0])), parameter);
Expression<Func<TSource, string>> field = Expression.Lambda<Func<TSource, string>>(expression, parameter);
return source.Like(field, textToFind);
}
Now this code doesn't work! I need to understand how to declare the "field" of the Like extended methods.
Expression<Func<TSource, string>> field = Expression.Lambda<Func<TSource, string>>(expression, parameter);
At runtime I receive this error: Impossibile utilizzare un'espressione di tipo 'System.Func`2[TestMdf.Equipment,System.String]' per un tipo restituito 'System.String'