I have been using the following code to inject "Odata" style parameters into a query. This works fine until I try to using $expand, and I get a casting error
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectAllAndExpand
1[STOS.Repository.Entities.Item]]' to type 'System.Collections.Generic.IEnumerable`1[STOS.Repository.Entities.Item]'.
public static List<T> ApplyTo<T>(HttpRequestMessage request, IQueryable<T> query)
{
var context = new ODataQueryContext(TheEdmModel(), typeof(T));
var newOptions = new ODataQueryOptions<T>(context, request);
return ((IEnumerable<T>)newOptions.ApplyTo(query)).ToList();
}
I understand that when $expand is used, a different wrapper class is returned, but how do I convert this to a List?
Please follow this sample https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataQueryableSample/ : public class OrderController : ApiController
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
// Register a custom FilterByValidator to disallow custom logic in the filter query
if (queryOptions.Filter != null)
{
queryOptions.Filter.Validator = new RestrictiveFilterByQueryValidator();
}
// Validate the query, we only allow order by Id property and
// we only allow maximum Top query value to be 9
ODataValidationSettings settings = new ODataValidationSettings(){ MaxTop = 9 };
settings.AllowedOrderByProperties.Add("Id");
queryOptions.Validate(settings);
// Apply the query
return queryOptions.ApplyTo(OrderList.AsQueryable()) as IQueryable<Order>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With