I am trying to test the ASP.NET Web API OData V4 $filter functionality.
I could map a non- nested filter query against a DTO to another entity easily following the answer here without using AutoMapper.
But I want to map a nested filter query to a non-complex DTO.
eg. mapping ?$filter= SubProperties/Amount eq 100
against a DTO which has Amount
field under SubProperties
class and then further map it to a target DTO which has Amount
property not nested.
GET products?$filter=SubProperties/Amount eq 100`
The Product class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Level { get; set; }
public Properties SubProperties {get;set;}
}
public class Properties
{
public double Amount{ get; set; }
}
The ProductDTO class:
public class ProductDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int Level { get; set; }
public double Amount { get; set; }
}
The ProductsController:
public class ProductsController : ApiController
{
public IEnumerable<ProductDTO> Get(ODataQueryOptions<Product> options)
{
IQueryable<Product> products = this._products.AsQueryable();
IEdmModel model = GetProductDTOModel();
IEdmType type = model.FindDeclaredType(typeof(ProductDTO).ToString());
ODataQueryOptionParser parser = new ODataQueryOptionParser(model, type, null, new Dictionary<string, string> { { "$filter", options.Filter.RawValue } });
ODataQueryContext context = new ODataQueryContext(model, typeof(Product), options.Context.Path);
FilterQueryOption filterMapper = new FilterQueryOption(options.Filter.RawValue, context, parser);
}
}
When I expand on options -> Filter it has mapped correctly to the filter query string and FilterClause loads correctly. But after mapping it to ProductsDTO and expanding on filterMapper , FilterClause throws an exception, since it doesn't have a property SubProperties.