likestoski
likestoski

Reputation: 1911

Apply IQueryable filter to parent and child collection in WebApi

I am using the IQueryable features in WebApi requests to deliver search results. I have based my code off this article. Is it possible to use the IQueryable on not only a parent object but also a collection of child objects?

For example using the example in this article it's possible to return queries for a Product. If the Product class has a collection of Categories would it be possible to perform IQueryable operations on the Product and it's collection of Categories? Something like Products?$filter=Category.Name eq 'Toys' and Price lt 10

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
    public IEnumerable<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Upvotes: 0

Views: 660

Answers (1)

Youssef Moussaoui
Youssef Moussaoui

Reputation: 12395

It should work. Try a URL like this instead though:

Products?$filter=Categories/any(category: category/Name eq 'Toys') and Price lt 10

This basically says "Find all the products with at least one category that has the name 'Toys' and price less than 10".

Upvotes: 1

Related Questions