zhelyazko
zhelyazko

Reputation: 57

Get items count from OData api

I'm working on ASP.NET Core 3.1 project where I use OData for the rest api. The problem is that when I try to fetch the count of the items in the collection with this query: http://someurl?$count=true, OData returns me an array of all the items, instead of the count. I read a lot of articles about OData and nothing helped, so I'm quite confused.

Upvotes: 0

Views: 744

Answers (1)

Xueli Chen
Xueli Chen

Reputation: 12715

Here is a working demo , you could refer to

Install Package Microsoft.AspNetCore.OData -Version 7.4.0

Model

 public class Student
{

    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Score { get; set; }
}

Controller , EnableQuery attribute enables an endpoint to have OData capabilities

[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
    [HttpGet]
    [EnableQuery()]
    public IEnumerable<Student> Get()
    {
        return new List<Student>
        {
            new Student
            {
                Id = Guid.NewGuid(),
                Name = "Vishwa Goli",
                Score = 100
            },
            new Student
            {
                Id = Guid.NewGuid(),
                Name = "Josh McCall",
                Score = 120
            }
        };
    }
}

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(mvcOptions =>
            mvcOptions.EnableEndpointRouting = false);

        services.AddOData();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapControllers();
        //});
        app.UseMvc(routeBuilder =>
        {
           // enable Selection, Expansion, Count, Filter, OrderBy for all routes under “odata/”
            routeBuilder.Expand().Select().Count().OrderBy().Filter();
            routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel());
        });
    }

    private IEdmModel GetEdmModel()
    {
        var edmBuilder = new ODataConventionModelBuilder();
        edmBuilder.EntitySet<Student>("Students");

        return edmBuilder.GetEdmModel();
    }

Result: enter image description here

Reference:

https://devblogs.microsoft.com/odata/experimenting-with-odata-in-asp-net-core-3-1/

https://medium.com/@sddkal/using-odata-controller-in-net-core-apis-63b688585eaf

Upvotes: 1

Related Questions