如何在$ expand中使用ODataQueryOptions

时间:2014-04-20 00:14:02

标签: asp.net-web-api odata

我一直在使用以下代码将“Odata”样式参数注入查询中。这工作正常,直到我尝试使用$ expand,我得到一个转换错误

无法转换类型为'System.Data.Entity.Infrastructure.DbQuery 1[System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectAllAndExpand 1 [STOS.Repository.Entities.Item]]'的对象,以输入'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();
    }

我理解当使用$ expand时,会返回一个不同的包装类,但是如何将其转换为List?

1 个答案:

答案 0 :(得分:1)

请按照此示例https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataQueryableSample/: 公共类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>;
}