使用Linq to SQL将fieldexexpression转换为LambdaExpression错误

本文关键字:转换 LambdaExpression 错误 fieldexexpression Linq to SQL 使用 | 更新日期: 2023-09-27 18:09:36

运行以下代码时,我得到错误Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.LambdaExpression'

这段代码的目的是允许我过滤记录(实体框架代码优先/Linq到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; }
    }
}

有什么建议我可以重写这个以避免上面的错误吗?

注:code也在CodeReview作为我最初的问题有关重构。https://codereview.stackexchange.com/questions/54888/refactor-c-linq-code-to-reduce-duplication

使用Linq to SQL将fieldexexpression转换为LambdaExpression错误

fielexpression不是LambdaExpression。你可以把它作为表达式的主体。在调试器中,您可以尝试以下操作来探索LambdaExpression的结构:

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

然后在调试器中,查看LambdaExpression类型的f,以及LambdaExpression的Body,它是字段表达式。