Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ODataQueryOptions with $expand

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+SelectAllAndExpand1[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?

like image 541
Salguod Avatar asked Apr 20 '14 00:04

Salguod


1 Answers

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>;
}
like image 144
Tan Jinfu Avatar answered Nov 10 '22 02:11

Tan Jinfu