如何获得项目总数

如何获得项目总数

本文介绍了.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();
            });

在我的控制器类中:

        [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}]

我想要的结果是:

[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:如何获得项目总数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 04:25