user3818229
user3818229

Reputation: 1647

Get items by matching predicate method

I'm trying to implement a generic method with predicate. I wrote some code:

public ICollection<T> GetProductsByMatching<T>(Expression<Func<T, bool>> predicate)
{
    return context.Products.Where(predicate).Include("ShopPlace, Images").ProjectTo<T>().ToList();
}

And usage of this method:

var a = service.GetProductsByMatching<ProductInfo>(x => x.Name.StartsWith("value") 
        || x.Price < 150);

Finally I have Invalid Operation Exception: No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments.

Whats wrong with my code? Thanks for advance!

Upvotes: 1

Views: 214

Answers (1)

CodeCaster
CodeCaster

Reputation: 151720

The predicate in context.Products.Where(predicate) can obviously only be an Expression<Func<Product, bool>>, not a Expression<Func<T, bool>>, because there's no guarantee that T is a Product.

You're trying to filter on the a predicate on the destination type, while the filtering must occur on the source type:

public ICollection<T> GetProductsByMatching<T>(Expression<Func<Product, bool>> predicate)
{
    return context.Products.Where(predicate)
                           .Include("ShopPlace, Images")
                           .ProjectTo<T>()
                           .ToList();

}

Upvotes: 3

Related Questions