简体   繁体   中英

Filtering EF LINQ based on dynamic condition

  • Using Entity Framework 6, Repository pattern with domain model
  • I want to filter products (a model) based upon if the user has selected a currency (which is linked into products via a FK)
  • The filter would apply to a separate object (a table) for the currency
  • I was thinking of creating an IQueryable extension method, but as it's a custom type, and only in the Product object due to a FK, I don't think this would work

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM