Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression'
运行以下代码时出现错误。
此代码的目的是允许我过滤包含某些字符串的记录(实体框架代码优先/Linq to SQL)。
注意:我正在使用第三方库 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; }
}
}
关于如何重写它以避免上述错误的任何建议?
注意:CodeReview 上的代码也是我与重构相关的原始问题。 https://codereview.stackexchange.com/questions/54888/refactor-c-linq-code-to-reduce-duplication