WebApi OData:$ filter'any'或'all'查询不起作用

时间:2013-03-18 11:21:34

标签: entity-framework asp.net-web-api odata

首先,使用ASP.NET WebApi教程我创建了一个基本的ApiController that exposes an Entity Framework model through OData。该服务用于返回json以进行OData $过滤查询。

当我对多值属性执行OData $filter queries that include "any" or "all"查询时,它会抛出ODataException

这是我正在尝试使用的OData查询

~/api/Blogs?$filter=any(Tags,Name+eq+'csharp')

我的ApiController看起来像这样:

public class BlogController : ApiController
{
    public BlogsController()
    {
        this.Entities = new BlogEntities();
    }

    public ContactEntities Entities { get; set; }

    [Queryable(PageSize = 25, AllowedQueryOptions = AllowedQueryOptions.All)]
    public IQueryable<Blog> Get()
    {
        return this.Entities.Blogs;
    }
}

博客实体有此合同

public Blog {
    public Guid ID { get; set; }
    public string Title { get; set; }
    public Tag Tags { get; set; }
}

public Tag {
    public Guid ID { get; set; }
    public string Name { get; set; }
}

抛出异常

ODataException: Type 'Blog' does not have a property 'Name'

正如您所看到的,我的代码中没有任何异常,一切都应该正常工作。 Microsoft ASP.NET Web API OData中是否可能不支持“任何”和“所有”查询?

1 个答案:

答案 0 :(得分:17)

你的任何需要改变一下。尝试这样的事情:

~/api/Blogs?$filter=Tags/any(tag: tag/Name eq 'csharp')

这假设标签实际上返回了一组标签,而不仅仅是上面的单个标签。

$ inlinecount仅支持OData格式的开箱即用。我在这里写了很多关于它的文章:

Web API OData Inlinecount not working

简短的回答是,您可以使用其他格式使用其代码如下:

public PageResult<Customer> Get(ODataQueryOptions<Customer> queryOptions)
{
    IQueryable results = queryOptions.ApplyTo(_customers.AsQueryable());
    return new PageResult<Customer>(results as IEnumerable<Customer>, Request.GetNextPageLink(), Request.GetInlineCount());
}