实体框架不支持表达式树

本文关键字:表达式 不支持 框架 实体 | 更新日期: 2023-09-27 18:22:04

我尝试使用自定义表达式对可查询集合进行排序:

.Lambda #Lambda1<System.Func`2[MyProject.Client,System.Object]>(MyProject.Client $var1)
{
    .Block() {
        .If ($var1.Legal == null) {
            .Return #Label1 { (System.Object)($var1.Person).Email }
        } .Else {
            .Return #Label1 { (System.Object)($var1.Legal).Email }
        };
        .Label
            .Constant<System.Object>(System.Object)
        .LabelTarget #Label1:
    }
}

然而,当尝试将我的集合强制转换为列表时,应用程序抛出异常:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: Unknown LINQ expression of type 'Block'.

UPD到Stilgar

我使用条件表达式。我的分拣扩展:

public static IOrderedQueryable<TSource> SortMultipleField<TSource>(this IQueryable<TSource> source, string propNames, bool ascending)
{
    var type = typeof(TSource);
    var param = Expression.Parameter(type);
    var sortFields = propNames.Split(',');
    Expression firstParent = param;
    var firstFieldPath = sortFields[0].Split('.');
    foreach (var item in firstFieldPath)
        firstParent = Expression.Property(firstParent, item);
    firstParent = Expression.Convert(firstParent, typeof(object));
    Expression secondParent = param;
    foreach (var item in sortFields[1].Split('.'))
        secondParent = Expression.Property(secondParent, item);
    secondParent = Expression.Convert(secondParent, typeof(object));
    var check = Expression.Property(param, firstFieldPath[0]);
    var checkNullExpression = Expression.Equal(check, Expression.Constant(null, check.Type));
    var returnTarget = Expression.Label(typeof(object));
    var block = Expression.Block(
        Expression.IfThenElse(
            checkNullExpression,
            Expression.Return(returnTarget, secondParent),
            Expression.Return(returnTarget, firstParent)),
        Expression.Label(returnTarget, Expression.Constant(new object())));
    var sortExpression = Expression.Lambda<Func<TSource, object>>(block, param);
    if (ascending)
        return source.OrderBy(sortExpression);
    return source.OrderByDescending(sortExpression);
}

实体框架不支持表达式树

我认为实体框架不支持语句lambdas-only表达式。如果您能够以某种方式将if语句转换为条件表达式,那么您可能会更幸运。

您似乎正在尝试对多个属性进行排序。我认为使用ThenBy方法会更容易做到这一点。

是的。您认为实体框架是如何将您的自定义表达式转换为-ah-SQL的?

提示:不能。很简单。它告诉你。

我建议你放弃排序,让EF返回你要求的任何IEnumerable,然后对结果进行排序(这不是在SQL中发生的,而是使用LINQ for Objects,因为EF以IEnumeraable结尾)。这应该允许在内存中进行排序,在内存中.NET运行时可以从自定义表达式中获得意义。