【发布时间】:2014-08-03 18:09:51
【问题描述】:
在我的 WebAPI 2 Odata 项目中使用多个过滤器时遇到问题。
我们只想要 JSON 输出并且只有一种对象类型可供查询,因此我们将 url 设置为“/”,而无法使用不同的控制器。
我有一个要查询的对象,具有以下属性:
public class Content
{
public int Id { get; set; }
public string Title { get; set; }
public string Excerpt { get; set; }
public string Link { get; set; }
public IList<Tag> Tags { get; set; }
}
public class Tag
{
public string Id { get; set; }
public string Name { get; set; }
}
控制器代码如下所示:
public class ContentController : ApiController
{
private readonly IContentRepository _repository;
// constructor
public ContentController(IContentRepository repository)
{
_repository = repository;
}
[Queryable]
public IQueryable<Content> Index()
{
// IContentRepository.GetAll returns an IEnumerable List of Content
return _repository.GetAll().AsQueryable();
}
}
现在,我通过向存储库添加多个对象来模拟一些测试数据,这些对象具有多个标签,其值设置为(test1、test2 或 test3)。现在当我查询时
http://localhost:xxx?$filter=Tags/any(o: o/Id eq 'test1')
我得到所有标签/ID 设置为“test1”的对象。但是如果我查询
http://localhost:xxx?$filter=Tags/any(o: o/Id eq 'test1' and o/Id eq 'test2')
我没有得到任何结果(JSON 返回 = [])。但它应该返回具有两个标签的对象。
我做错了什么?
编辑: 我的示例数据 JSON 如下所示:
[
{
"Id": 1,
"Title": "TESTOBJECT 1",
"Excerpt": "",
"Link": "",
"Tags": [
{
"Id": "test1",
"Name": "Test Tag 1",
}
],
},
{
"Id": 2,
"Title": "TESTOBJECT 2",
"Excerpt": "",
"Link": "",
"Tags": [
{
"Id": "test2",
"Name": "Test Tag 2",
}
],
},
{
"Id": 3,
"Title": "TESTOBJECT 3",
"Excerpt": "",
"Link": "",
"Tags": [
{
"Id": "test3",
"Name": "Test Tag 3",
}
],
},
{
"Id": 4,
"Title": "TESTOBJECT 4",
"Excerpt": "",
"Link": "",
"Tags": [
{
"Id": "test1",
"Name": "Test Tag 1",
},
{
"Id": "test2",
"Name": "Test Tag 2",
}
],
},
{
"Id": 5,
"Title": "TESTOBJECT 5",
"Excerpt": "",
"Link": "",
"Tags": [
{
"Id": "test1",
"Name": "Test Tag 1",
}
],
}
]
现在查询 1 给了我对象 1,4,5,我希望查询 2 给我对象 4。如何使用 odata 来完成此操作?
【问题讨论】:
标签: filter odata asp.net-web-api2