在 Linq 中创建和调用 SqlFunctions 到实体 C#

本文关键字:SqlFunctions 实体 调用 Linq 创建 | 更新日期: 2023-09-27 18:34:28

我们希望使用表达式动态创建以下代码:

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'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"))}

表达式创建成功,但是当我们在 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.

在 Linq 中创建和调用 SqlFunctions 到实体 C#

请在下面找到链接

Linq 到实体查询的动态谓词

使用 LINQ 到实体和表达式进行动态查询

我可以找到解决方案:

我们不必自己使用Compile()。 我们要使用以下代码:

List<Employee> employees2 = entities.Employees.Where(expression).ToList();