Мы хотим динамически создать следующий код с помощью выражения:
TestDatabaseEntities entities = new TestDatabaseEntities();
entities.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); // to show generated tsql
// We wanna create the following line dynamically
List<Employee> employees = entities.Employees.Where(c => SqlFunctions.StringConvert((double?)c.SomeNumber).Trim().Contains("123")).ToList();
Над кодом работает отлично. теперь мы хотим создать его с выражением динамически.
Мы сделали это следующим образом:
Type entityType = typeof(TEntity);
ParameterExpression parameterExpression = Expression.Parameter(entityType, "entity");
Type nullableDoubleType = typeof (double?);
//leftSile == {entity.SomeNumber}, it 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"))}
Выражение создано успешно, но когда мы используем его в EntityFramework, оно генерирует исключение:
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.
Я мог бы найти решение:
Нам не нужно использовать Compile()
самостоятельно. мы хотим использовать следующий код:
List<Employee> employees2 = entities.Employees.Where(expression).ToList();
Ниже приведены ссылки