问题
I've created a new .NET Core 2.2 web app, using OData v7.1.
I've got it up and running and can already use $top, $skip, ...
I'm trying to get $count to work properly now, but I'm completely lost at how to do it.
I've already tried following several links, all of them either no longer compile, or do not produce the result I want.
What I have :
in StartUp.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
routes.EnableDependencyInjection();
routes.Expand().Select().OrderBy().Filter().MaxTop(null).Count();
});
in my Controller class:
[EnableQuery]
[HttpGet("[action]")]
public IActionResult All()
{
var assets = _service.GetAllAssets();
return Ok(assets);
}
This returns all assets and I can use $top and $skip no problem. Now how do I add $count=true, or any other method that will allow me to also return my total count? What am I doing wrong?
Sample url that works: http://localhost/api/Assets/All?$top=20&$skip=20
Url that does not work: http://localhost/api/Assets/All?$count=true (it returns all assets)
The current result is:
[{Item One}, {Item Two}]
The desired result for me would be:
[Count : 4,
Items: [{Item One}, {Item Two}
]
回答1:
You can do like this:
public IActionResult GetData(ODataQueryOptions<YourType> query)
{
var data = _context.SetOfYourType;
return Ok(new
{
Items = query.ApplyTo(data),
Count = query.Count?.GetEntityCount(query.Filter?.ApplyTo(data, new ODataQuerySettings()) ?? data)
});
}
This is basically produce the same result as using PageResult, at least in terms of $expand,$select and $count.
回答2:
You return wrong type, go this way:
[EnableQuery]
[HttpGet("[action]")]
public IQueryable<YourType> All()
{
var assets = _service.GetAllAssets(); //Where assets is IQueryable
return assets;
}
OData middleware will made rest for you. Also in this approach if you make skip/take/select it is evaluate on SQL level.
来源:https://stackoverflow.com/questions/56221207/odata-in-net-core-2-2-how-to-get-total-number-of-items