1

我正在使用 EF 并希望向 WCF 服务传递一个过滤器功能。如果我有一个过滤器,一切都很好,但是当我尝试将一些表达式组合在一起时,我得到一个令人讨厌的错误:底层连接已关闭:服务器关闭了一个预期保持活动状态的连接。

所以这是我的过滤器对象:

public class EventFilter
{
    public int CategoryId { get; set; }
    public int SubCategoryId { get; set; }
    public DateTime StartDate { get; set; }
    public int? Duration { get; set; }
    public string Address { get; set; }
}

这是可以正常工作的过滤器功能(一个过滤器):

public IQueryable<Event> GetBySearch(EventFilter search)
{
    Expression<Func<Event, bool>> where = null;

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

    return this.Context.Events.Where(where);
}

但是如果我想为两个过滤器扩展它,它就不起作用,我不明白如何修复它。

所以,这是组合功能,我认为没问题。

private static Expression<Func<TEntity, bool>> Combine<TEntity>(Expression<Func<TEntity, bool>> a, Expression<Func<TEntity, bool>> b)
{
    var and = Expression.AndAlso(a.Body, b.Body);
    var param = Expression.Parameter(typeof(TEntity));

    return Expression.Lambda<Func<TEntity, bool>>(and, param); ;
}

这是问题过滤器功能(当两个过滤器都发生时它不起作用:

public IQueryable<Event> GetBySearch(EventFilter search)
{
    Expression<Func<Event, bool>> where = null;

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

    if (search.SubCategoryId != 0)
    {
        where = Combine<Event>(where, x => x.SubCategoryId == search.SubCategoryId);;
    }

    return this.Context.Events.Where(where);
}

我尝试了很多不同的方法,我尝试在结果中输入一个新对象,例如:

public IQueryable<Event> GetBySearch(EventFilter search)
{
    Expression<Func<Event, bool>> where = null;
    Expression<Func<Event, bool>> where2 = null;

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

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

    var result = Combine(where, where2);

    return this.Context.Events.Where(result);
}

毕竟我注意到这段代码有效:

Expression<Func<Event, bool>> where3 = (x => x.CategoryId == search.CategoryId) && (x => x.SubCategoryId == search.SubCategoryId);

虽然这不是:

Expression<Func<Event, bool>> where3 = where && where2; //Compile time error.

也许问题从这里开始,有人可以帮助我吗?谢谢 !!!

4

1 回答 1

2

因为多个Where子句是AND一起编辑的,并且每个子句都返回 a ,所以IQueryable<Event>您可以像这样将多个子句链接在一起。

public IQueryable<Event> GetBySearch(EventFilter search)
{
    IQueryable<Event> events = this.Context.Events; //(I assume Events is an IQueryable<Event>)

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

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

    return events;
}

这有效地做到了(假设两个 id 都不是 0)

this.Context.Events.Where(x => x.CategoryId == search.CategoryId).Where(x => x.SubCategoryId == search.SubCategoryId);

这与

this.Context.Events.Where(x => x.CategoryId == search.CategoryId && x.SubCategoryId == search.SubCategoryId);
于 2013-08-21T15:49:53.970 回答