Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression'
以下のコードを実行するとエラーが発生します。
このコードの目的は、特定の文字列を含むレコード (Entity Framework Code First / 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.