9

我只想构建一个动态过滤器。最后返回

 Expression<Func<Event, bool>>

我尝试使用 Combine (AndAlso) 表达式,但它不起作用,最后我发现有 IQueryable 查询效果很好,但现在我怎样才能将它转换为返回类型 -

Expression<Func<Event, bool>>?

我的代码:

    public IQueryable<Event> GetBySearch(EventFilter search)
    {
        IQueryable<Event> query = this.Context.Events.AsQueryable();
        Expression<Func<Event, bool>> expression = null;

        if (search.CategoryId != 0)
        {
            query = query.Where(x => x.CategoryId == search.CategoryId);
        }

        if (search.SubCategoryId != 0)
        {
            query = query.Where(x => x.SubCategoryId == search.SubCategoryId);
        }

        expression = query.Expression as Expression<Func<Event, bool>>; //This convert is not working, it returns null.

        return this.Context.Events.Where(expression);
    }
4

2 回答 2

7

您不只是执行以下操作的任何原因:

public IQueryable<Event> GetBySearch(EventFilter search)
{
    IQueryable<Event> query = this.Context.Events.AsQueryable();

    if (search.CategoryId != 0)
    {
        query = query.Where(x => x.CategoryId == search.CategoryId);
    }

    if (search.SubCategoryId != 0)
    {
        query = query.Where(x => x.SubCategoryId == search.SubCategoryId);
    }

    return query;
}

正如 Florian 在评论中所说,应避免返回 IQueryables(如果可能)。简单的解决方案是返回一个列表:

public List<Event> GetBySearch(EventFilter search)
{
    IQueryable<Event> query = this.Context.Events.AsQueryable();

    if (search.CategoryId != 0)
    {
        query = query.Where(x => x.CategoryId == search.CategoryId);
    }

    if (search.SubCategoryId != 0)
    {
        query = query.Where(x => x.SubCategoryId == search.SubCategoryId);
    }

    return query.ToList();
}
于 2013-08-22T08:24:23.257 回答
2

此转换无效,因为Where将其转换为MethodCallExpression

这将是有效的:

MethodCallExpression e = query.Expression as MethodCallExpression;
于 2013-08-22T08:25:04.013 回答