不幸的是,Web API 还不支持 $count 开箱即用,尽管它应该在未来的版本中。同时,您仍然可以通过定义这些类来添加支持:
public class CountODataRoutingConvention : EntitySetRoutingConvention
{
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (controllerContext.Request.Method == HttpMethod.Get && odataPath.PathTemplate == "~/entityset/$count")
{
if (actionMap.Contains("GetCount"))
{
return "GetCount";
}
}
return null;
}
}
public class CountODataPathHandler : DefaultODataPathHandler
{
protected override ODataPathSegment ParseAtEntityCollection(IEdmModel model, ODataPathSegment previous, IEdmType previousEdmType, string segment)
{
if (segment == "$count")
{
return new CountPathSegment();
}
return base.ParseAtEntityCollection(model, previous, previousEdmType, segment);
}
}
public class CountPathSegment : ODataPathSegment
{
public override string SegmentKind
{
get
{
return "$count";
}
}
public override IEdmType GetEdmType(IEdmType previousEdmType)
{
return EdmCoreModel.Instance.FindDeclaredType("Edm.Int32");
}
public override IEdmEntitySet GetEntitySet(IEdmEntitySet previousEntitySet)
{
return previousEntitySet;
}
public override string ToString()
{
return "$count";
}
}
在 MapODataRoute 中注册它们:
IList<IODataRoutingConvention> routingConventions = ODataRoutingConventions.CreateDefault();
routingConventions.Insert(0, new CountODataRoutingConvention());
config.Routes.MapODataRoute("OData", "odata", GetModel(), new CountODataPathHandler(), routingConventions);
在您的控制器中,添加此方法:
public HttpResponseMessage GetCount(ODataQueryOptions<TEntity> queryOptions)
{
IQueryable<TEntity> queryResults = queryOptions.ApplyTo(Get()) as IQueryable<TEntity>;
int count = queryResults.Count();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(count.ToString(), Encoding.UTF8, "text/plain");
return response;
}
为了避免必须将 GetCount() 复制到每个控制器,您可以定义一个派生自定义 GetCount 的 EntitySetController 的基类。