Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
We wanna create the following code dynamically with expression:

C#
TestDatabaseEntities entities = new TestDatabaseEntities();
entities.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); // to show generated tsql
// We wanna create the following code dynamically
List<Employee> employees = entities.Employees.Where(c => SqlFunctions.StringConvert((double?)c.SomeNumber).Trim().Contains("123")).ToList();


Above code works great. now we wanna create it with expression dynamically.

We done it as follows :

C#
Type entityType = typeof(TEntity);
ParameterExpression parameterExpression = Expression.Parameter(entityType, "entity");

Type nullableDoubleType = typeof (double?);
//leftSile == {entity.SomeNumber}, it's OK
UnaryExpression unaryExpression  = Expression.Convert(leftSile, nullableDoubleType);
MethodInfo stringConvertMethodInfo = typeof(SqlFunctions).GetMethod("StringConvert", new[] { nullableDoubleType });
MethodInfo trimMethodInfo = typeof(string).GetMethod("Trim", new Type[] {});
ConstantExpression newRightSide = Expression.Constant(valueObject.ToString());

var traceVariable1 = Expression.Call(stringConvertMethodInfo, unaryExpression);
var traceVariable2 = Expression.Call(traceVariable1, trimMethodInfo);
Expression resultExpression = Expression.Call(traceVariable2, methodInfo, newRightSide);
Expression<Func<Employee, bool>> expression = Expression.Lambda<Func<TEntity, bool>>(resultExpression, parameterExpression);

// expression == {entity => (StringConvert(Convert(entity.SomeNumber)).Trim().Contains("123"))}


The expression created successfully, but when we use it within EntityFramework it throws an exception:

C#
List<Employee> employees2 = entities.Employees.Where(expression.Compile()).ToList();
//Exception :
//An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll
//Additional information: This function can only be invoked from LINQ to Entities.
Posted
Comments
Maciej Los 24-Mar-15 3:31am    
Have you tried to convert below query without SqlFunctions?
List<Employee> employees = entities.Employees.Where(c => string.Convert(c.SomeNumber).Trim().Contains("123")).ToList();

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900