实体框架不支持表达式树

时间:2014-09-16 07:13:19

标签: c# linq entity-framework expression-trees

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

.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 to 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);
}

2 个答案:

答案 0 :(得分:4)

我相信Entity Framework不支持语句lambdas only表达式。如果你能以某种方式将if语句转换为conditional expression,那么你可能会有更多的运气。

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

答案 1 :(得分:-2)

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

提示:它不能。就像这样。它告诉你。

我建议你废弃排序,得到EF返回你要求的任何IEnumerable,然后排序结果(然后不是在SQL中使用LINQ for Objects,因为EF在IEnumerable结束)。这应该允许在内存中进行排序,其中.NET运行时可以从您的自定义表达式中理解。