What I'd prefer to avoid (as I have quite a few methods that query Products)
public bool DoesUniqueHaveChildProducts(string productName, int brandId)
{
if (UserCurrency.userCurrency == -1)
{
//don't filter
return _db.Products.Any(x => x.BrandID == brandId && x.Name.Contains(productName));
}
return _db.Products.Any(x => x.BrandID == brandId && x.Name.Contains(productName) && x.MasterSite.CurrencyID == UserCurrency.userCurrency);
}
Looking for ideas & suggestions
Thanks!
This should work for you:
Func<Product, bool> predicate = x => x.BrandID == brandId && x.Name.Contains(productName);
if (UserCurrency.userCurrency != -1)
{
predicate = x => x.BrandID == brandId &&
x.Name.Contains(productName) &&
x.MasterSite.CurrencyID == UserCurrency.userCurrency;
}
return _db.Products.Any(predicate);
In each case Queryable<TModel>.Any
takes an argument of type Expression<Func<TModel, bool>>
.
So you could just put the condition in a local:
Expression<Func<TModel, bool>> pred;
if (whatever) {
pred = m => Condition(m)
} else {
pred = m => OtherCondition(m)
}
return db.Products.Any(pred);
which might be be cleaner (depends on the sitution).
It is also possible to build an Expression<whatever>
dynamically, but like reflection that can be a lot of code... making use of the types in System.Linq.Expressions
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.