Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error casting FieldExpression to LambdaExpression using Linq to SQL

I'm getting the error Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression' when running the below code.

The intent of this code is to allow me to filter records (Entity Framework Code First / Linq to SQL) for those containing certain strings.

NB: I'm using the third party library LinqKit: http://www.albahari.com/nutshell/predicatebuilder.aspx

FilterHelper<Country> helper = new FilterHelper<Country>();
helper.AddContains(searchAlpha2, c => c.Alpha2);
helper.AddContains(searchAlpha3, c => c.Alpha3);
helper.AddContains(searchName, c => c.Name);

IQueryable<Country> countries = db.Countries.AsExpandable().Where(helper.Predicate);

...

public class FilterHelper<T>
{
    public delegate string GetColumn<T>(T item);

    private Expression<Func<T,bool>> predicate; 

    public FilterHelper()
    {
        this.predicate = PredicateBuilder.True<T>();
    }
    public void AddContains(string searchText, GetColumn<T> getColumn)
    {
        if (!string.IsNullOrWhiteSpace(searchText))
            predicate = predicate.And(c => getColumn(c) != null ? getColumn(c).Contains(searchText) : false);
    }  
    public Expression<Func<T,bool>> Predicate
    {
        get { return this.predicate; }
    }

}

Any suggestions on how I could rewrite this to avoid the above error?

NB: code also on CodeReview as my original question related to refactoring. https://codereview.stackexchange.com/questions/54888/refactor-c-linq-code-to-reduce-duplication

like image 786
JohnLBevan Avatar asked Nov 10 '22 06:11

JohnLBevan


1 Answers

A FieldExpression is not a LambdaExpression. You can make one as the body of an expression. In the debugger you can try the following to explore the structure of a LambdaExpression:

Expression<Func<U,T>> f = t => t.FieldName;

then in the debugger, look at f, which is of type LambdaExpression, and the Body of LambdaExpression which is Field Expression.

like image 123
Gordon Avatar answered Nov 14 '22 21:11

Gordon