I'm attempting to write an expression tree which supports dynamic use of StartsWith on number values. The idea is to use this method to build dynamic where queries, based on a user input, and execeute them against EF 6. I’ve already written a method which works for String values. Can you help me to make the same for non-string values?
Here is what my method looks like:
public static IQueryable<TEntity> WhereDynamic<TEntity>( IQueryable<TEntity> queryable, String propertyName,
String queryValue )
{
var startsWithMethodInfo = typeof ( String ).GetMethod( "StartsWith", new[]
{
typeof ( String )
} );
var parameterExpression = Expression.Parameter( typeof ( TEntity ), "x" );
var field = Expression.PropertyOrField( parameterExpression, propertyName );
var startsWith = Expression.Call( field, startsWithMethodInfo, Expression.Constant( queryValue ) );
var expression = Expression.Lambda<Func<TEntity, bool>>( startsWith, parameterExpression );
return queryable.Where( expression );
}
I know that I can use the SqlFunctions.StringConvert method to use StartsWith on number values, but I don’t know how to include it in the expression tree.
Update
The code I’ve posted works perfectly, but only for String types. Now I want to change it to work with non-string types as well. The problem why it is now not working for numbers is that EF does not support StartsWith for non-string types. This problem can be fixed with a call to SqlFunctions.StringConvert:
movies = movies.Where( y => SqlFunctions.StringConvert(
(Double) y.MovieId).TrimStart().StartsWith( "123" ) );
But I don’t know how I can include a call to SqlFunctions.StringConvert in the Expression Tree. So my question is: How can I change the code above to work with none-string types?