Jay
Jay

Reputation: 2244

How to get Paging info and a single record when using OData in ASP.NET 5 WebAPI

I have a web API written using C# on the top of ASP.NET 5/Core with EntityFrameworkCore.

I am using OData to apply filters on when querying the database.

Currently, I am allowing query options by doing this in my controller

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly DbContext _db;

    public ProductsController(DbContext db)
    {
        _db = db;
    }

    [HttpGet]
    [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All, AllowedFunctions = AllowedFunctions.AllFunctions, MaxTop = 500)]
    public IQueryable<TModel> Search()
    {
        return db.Products;
    }

    [HttpGet]
    [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All, AllowedFunctions = AllowedFunctions.AllFunctions)]
    public TModel First()
    {
        // How could I apply the query filters here before I execute the query?
        return db.Products.FirstOrDefault();
    }
}

Questions

In the Search action, how can I return the records in addition to the paganing info like totalPagesAvailable and totalRecordsAvailable?

In the First action, how can I apply the query filters to the query before I return the first matching record?

Upvotes: 2

Views: 174

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

Try the following:

[HttpGet]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All, AllowedFunctions = AllowedFunctions.AllFunctions)]
public Product First(ODataQueryOptions<Product> queryOptions)
{
    var query = (IQueryable<Product>)queryOptions.ApplyTo(db.Products);
    return query.FirstOrDefault();
}

Upvotes: 2

Related Questions