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