【问题标题】:WebApi OData: $filter 'any' or 'all' query not workingWebApi OData:$filter 'any' 或 'all' 查询不起作用
【发布时间】:2013-03-06 17:12:12
【问题描述】:

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

当我对多值属性执行 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 中是否可能还不支持“任何”和“所有”查询?

【问题讨论】:

  • 另一件值得注意的是,'$inlinecount' odata 选项被忽略了。

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


【解决方案1】:

您的任何内容都需要稍作更改。试试这样的:

~/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());
}

【讨论】:

  • 谢谢,伙计!在测试了您的建议后,我查看了 OData 规范……好吧,我应该先阅读一下。
  • $inlinecount 答案不适用于继承“ApiController”的服务
  • 我刚刚再次测试了它——它有效。请包含您的代码和您使用的 URL。
  • 但是 ApiController 有一个 Request 属性。您必须为 System.Net.Http 命名空间添加 using 才能获取其他方法。
猜你喜欢
  • 1970-01-01
  • 2014-03-15
  • 2012-03-19
  • 2018-07-24
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
相关资源
最近更新 更多