I have been learning Expressions and using the code below to add build up an expression against a database model (EF4 – ORACLE not SQL!)
This works perfectly against Oracle, and allows me to dynamically build up predicates such as "CustomerId", "Contains", 2 into f=>f.CustomerId.ToString().ToLower().Contains("2")
However, if I try against SQL Server then it fails because I need to call SqlFunctions.StringConvert – but I don’t know how to get that included in the Lambda?
My end result would be something like:
f=> SqlFunctions.StringConvert(f.CustomerId).ToLower().Contains("2")
Thx 🙂
EDIT: Added example of what I have tried
This code looks like it almost works, sort of!
However, it throws an error on the var sqlExpression line
Expression of type 'System.Double' cannot be used for parameter of type 'System.Nullable`1[System.Double]' of method 'System.String StringConvert(System.Nullable`1[System.Double])'
MethodInfo convertDouble = typeof(Convert).GetMethod("ToDouble",new Type[]{typeof(int)});
var cExp = Expression.Call(convertDouble, left.Body);
var entityParam = Expression.Parameter(typeof(TModel), "f");
MethodInfo sqlFunc = typeof(SqlFunctions).GetMethod("StringConvert", new Type[] { typeof(double) });
var sqlExpression = Expression.Call(sqlFunc, cExp);
MethodInfo contains = typeof(string).GetMethod("Contains", new[] { typeof(string) });
right = Expression.Constant(value.ToString(), typeof(string));
var result = left.AddToString().AddToLower().AddContains(value.ToString());
return result;
public static Expression<Func<T, string>> AddToString<T, U>(this Expression<Func<T, U>> expression)
{
return Expression.Lambda<Func<T, string>>(
Expression.Call(expression.Body,
"ToString",
null,
null),
expression.Parameters);
}
public static Expression<Func<T, string>> AddToLower<T>(this Expression<Func<T, string>> expression)
{
return Expression.Lambda<Func<T, string>>(
Expression.Call(expression.Body,
"ToLower",
null,
null),
expression.Parameters);
}
public static Expression<Func<T, bool>> AddContains<T>(this Expression<Func<T, string>> expression, string searchValue)
{
return Expression.Lambda<Func<T, bool>>(
Expression.Call(
expression.Body,
"Contains",
null,
Expression.Constant(searchValue)),
expression.Parameters);
}
I believe you basically need to build an equivalent expression of the following lambda expression:
Here is a full copy-paste example. It uses CodeFirst so should work without having to create database or anything like that. Just add the Entity Framework nuget package (I used EF6 but it should work for EF5 as well). Build lambda is what you are really after.