Entity Framework not support expression trees

c# entity-framework expression-trees linq


I attempt to use a custom expression to sort my queryable collection.

.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 }
        .LabelTarget #Label1:

However, the program produces an error when I try to cast my collection to the list:

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'.

to Stilgar UPD

Conditional expression is what I utilize. I'll sort by extension:

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.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);
9/16/2014 7:29:57 AM

Popular Answer

Only expressions, in my opinion; statement lambdas are not supported by Entity Framework. If you can somehow change the if statement into a expression of condition, you could have better results.

You seem to be attempting to sort on many different criteria. ThenBy would, in my opinion, make this process simpler.

9/16/2014 7:44:03 AM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow