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


首先,使用ASP.NET WebApi教程,我创建了一个基本的 通过OData公开实体框架模型的ApiController。该服务用于返回json以进行OData $过滤查询。

当我执行OData时 $ filter查询包含“any”或“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


1294
2018-03-18 11:21


起源

值得注意的另一件事是'$ inlinecount'odata选项被忽略了。 - Chris Pietschmann


答案:


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

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

这假设Tags实际上返回了一个Tags集合,而不仅仅是像上面一样的单个Tag。

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

Web API OData Inlinecount无法正常工作

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

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

16
2018-03-18 12:32



谢啦!!在测试了你的建议后,我查看了OData规范......好吧,我只想说我应该先阅读。 - Chris Pietschmann
$ inlinecount答案不适用于继承“ApiController”的服务 - Chris Pietschmann
我刚刚测试了它 - 它的工作原理。请包含您的代码和您使用的URL。 - Youssef Moussaoui
ApiController没有“GetNextPageLink”和“GetInlineCount”方法...... - Chris Pietschmann
但是ApiController有一个Request属性。您必须为System.Net.Http命名空间添加一个using来获取其他方法。 - Youssef Moussaoui