.Net Core 2.2中的OData:如何获取项目总数? [英] OData in .Net Core 2.2 : how to get total number of items?

查看:82
本文介绍了.Net Core 2.2中的OData:如何获取项目总数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用OData v7.1创建了一个新的.NET Core 2.2 Web应用程序.

I've created a new .NET Core 2.2 web app, using OData v7.1.

我已经启动并运行它,并且已经可以使用$ top,$ skip,...

I've got it up and running and can already use $top, $skip, ...

我试图使$ count现在可以正常工作,但是我完全不知道该怎么做.

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.

我有什么:

StartUp.cs

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");

                routes.EnableDependencyInjection();
                routes.Expand().Select().OrderBy().Filter().MaxTop(null).Count();
            });

在我的 Controller类中:

        [EnableQuery]
        [HttpGet("[action]")]
        public IActionResult All()
        {
            var assets = _service.GetAllAssets();
            return Ok(assets);
        }

这将返回所有资产,我可以使用$ top和$ skip没问题.现在如何添加$ count = true或任何其他可以返回总计数的方法?我究竟做错了什么?

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?

有效的示例网址: http://localhost/api/Assets/All ?$ top = 20& $ skip = 20

Sample url that works: http://localhost/api/Assets/All?$top=20&$skip=20

无效的网址: http://localhost/api/Assets/All ?$ count = true (它返回所有资产)

Url that does not work: http://localhost/api/Assets/All?$count=true (it returns all assets)

当前结果是:

[{Item One}, {Item Two}]

对我来说,理想的结果是:

The desired result for me would be:

[Count : 4, 
 Items: [{Item One}, {Item Two}
]

推荐答案

您可以这样做:

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

这基本上产生与使用PageResult相同的结果,至少在$ expand,$ select和$ count方面.

This is basically produce the same result as using PageResult, at least in terms of $expand,$select and $count.

这篇关于.Net Core 2.2中的OData:如何获取项目总数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆