在我的ODATA-v4控制器中,我有以下代码:
var fn = reportModelBuilder.EntityType<CurrentTestResult>()
.Collection.Function("Breakdown").Returns<int>();在CurrentTestResultController.cs中,我有一个看似简单的东西:
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
[HttpGet]
public IHttpActionResult Breakdown()
{
var count = dataService.GetAll()
.Select(x => x.TestResultTypeId)
.Distinct()
.Count();
return Ok(count);
}本质上,对于集合中的所有CurrentTestResult实体,它返回集合中出现的不同的TestResultTypeId。(这是一个琐碎的操作,但我简化了一个非常复杂的生活场景)
这是很容易做到的-但我似乎不能第一过滤集合的CurrentTestResult,它应该操作。
此请求,默认情况下对所有CurrentTestResult实体进行操作。
localhost/app/odatareport/CurrentTestResult/Default.Breakdown
返回
{
@odata.context: "http://localhost/app/odatareport/$metadata#Edm.Int32",
value: 5
}(一个正确的结果,有5种不同的类型)
但是,这个请求(它只是先过滤掉它)失败了。
localhost/app/odatareport/CurrentTestResult/Default.Breakdown?$top=2
返回
{
error: {
code: "",
message: "The query specified in the URI is not valid. The requested resource is not a collection. Query options $filter, $orderby, $count, $skip, and $top can be applied only on collections.",
innererror: {
message: "The requested resource is not a collection. Query options $filter, $orderby, $count, $skip, and $top can be applied only on collections.",
type: "Microsoft.OData.ODataException",
stacktrace:
" at System.Web.OData.EnableQueryAttribute.ValidateSelectExpandOnly(ODataQueryOptions queryOptions) at System.Web.OData.EnableQueryAttribute.ExecuteQuery(Object response, HttpRequestMessage request, HttpActionDescriptor actionDescriptor, ODataQueryContext queryContext) at System.Web.OData.EnableQueryAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)"
}
}
}就我所理解的ODATA管道而言,这一失败的原因是合理的。控制器方法将返回一个IQueryable,然后返回ODATA $filter、$top等。将被应用。
我想要一个函数来操作一个已经被过滤掉的集合。
是我想要做的,甚至是可能的?
我知道分解方法本身包含.GetAll(),但是必须有一种在方法之前应用过滤的方法-
否则,这一切都毫无意义.
发布于 2017-09-29 23:16:44
有两种选择:
1) ODATA有一个$count端点(参见这,但是有两种形式的$count --端点api/collection/$count和系统查询选项api/collection?$count=true;您需要端点),它返回集合的计数(可以用EnableQuery筛选)。将您的函数视为任何其他GET集合方法,并返回希望计数的查询(在本例中是不同的TestResultTypeId),然后只需要客户机请求其$count端点。
2)为操作方法定义一个ODataQueryOptions<T>参数,并手动应用这些选项:
public IHttpActionResult Get( ODataQueryOptions<CurrentTestResult> queryOptions )
{
// base query with ODataQueryOptions applied
var query = queryOptions.ApplyTo( dataServcie.GetAll() )
as IQueryable<CurrentTestResult>;
// get distinct TestResultTypeId's and then count
var count = query.Select(x => x.TestResultTypeId)
.Distinct()
.Count();
return Ok( count );
}我现在是移动的,所以不能测试,但这应该足够近(如果不是准确的话),让你去你需要去的地方。如果有任何问题,请告诉我,我会更新答案。
https://stackoverflow.com/questions/46458288
复制相似问题