3

I have to add the following to this filter,

"If the CountryID passed in equals (999) then the search should search all countries, and not filter by country."

what I currently have is this, which totally confuses me.

var query = rep.
    FindWhere(c => 
        (
            countryID.HasValue == false || 
            c.CityID == null || 
            c.Countries.ID == countryID
        )
        && 
        (
            mediaTypeID == 0 || 
            c.MediaTypeID == mediaTypeID
        ) 
        && c.Active);

I'm assuming that if any on the conditions in the first parantheses is true then it will match against all countries?! if so then I can add an extra expression in the first parantheses to check for countryID 999?

ps. FindWhere is:

public IQueryable<T> FindWhere(Expression<Func<T, bool>> predicate) 
{
    return _dbSet.Where(predicate);
}
4

2 回答 2

4
rep.FindWhere(c => (c.CityID == null || !countryID.HasValue ||
                    countryID == 999 || c.Countries.ID == countryID) &&
                   (mediaTypeID == 0 || c.MediaTypeID == mediaTypeID))

顺便说一句,您的条件逻辑真的很难理解。考虑重构您的代码。

于 2013-03-26T15:08:06.597 回答
3

我假设如果第一个括号中的任何条件为真,那么它将与所有国家/地区匹配?!如果是这样,那么我可以在第一个括号中添加一个额外的表达式来检查 countryID 999?

这应该有效。现在,谓词要求前三个条件中的任何一个为真(countryIDisnull或指定的国家,或城市 is null),然后检查第二个条件中的任何一个。

如果您使用 999 进行国家/地区检查,则添加针对 999 的检查将始终通过第一个标准,从而有效地“删除”过滤器。

话虽如此,我个人更愿意将其分解。由于您已经在使用IQueryable<T>,您可以选择性地添加过滤器:

var query = rep.FindWhere(c => c.Active);
if (mediaType != 0)
    query = query.Where(c => c.MediaTypeID == mediaTypeID);
if (countryID != 999)
    query = query.Where(c => countryID.HasValue == false || c.CityID == null || c.Countries.ID == countryID);

这更有效(您只在需要时添加过滤器),但也更容易理解。

于 2013-03-26T15:07:01.717 回答