OData In .NET 5


According to the people who designed it, OData (the Open Data Protocol) is "the best way to Rest".
OData is essential, a way to try and standardize REST. It's an open protocol that allows the creation and consumption of queryable and interoperable RESTful APIs in a simple and standard way. It describes things such as which HTTP method to use for which type of request, which status codes to return when, and also URL conventions. It includes information on querying data - filtering and paging but also calling custom functions and actions and more.
Query Options 
The following are the OData query options that ASP.NET Core WebAPI supports,
  1. $orderby
    Sorts the fetched record in a particular order like ascending or descending.

  2. $select
    Selects the columns or properties in the result set. Specifies which all attributes or properties to include in the fetched result.

  3. $skip
    Used to skip the number of records or results. For example, I want to skip the first 100 records from the database while fetching complete table data, then I can make use of $skip.

  4. $top
    Fetches only top n records. For  example,  I want to fetch the top 10 records from the database, then my particular service should be OData enabled to support the $top query option.

  5. $expand
    Expands the related domain entities of the fetched entities.

  6. $filter
    Filters the result set based on certain conditions, it is like where clause of LINQ. For example,  I want to fetch the records of 50 students who have scored more than 90% marks, and then I can make use of this query option.

  7. $inlinecount
    This query option is mostly used for pagination on the client-side. It tells the count of total entities fetched from the server to the client.
  • SDK - .Net 5.0
  • Tool - Visual Studio 2019

Setup Solution

Visual Studio 2019 is necessary to create the ASP.NET Core 5.0 web API or application. So, Let's select the "ASP.NET Core Web API" project template in the following dialog to create the skeleton of the project.
Click the "Next" button, then in the Additional information dialog, Select ".Net 5.0 template" for simplicity as below.
Click the "Create" button, we will get an empty ASP.NET Core Web API Project.

Install the NuGet Package

The first thing to install is to install the ASP.NET Core OData Nuget package and also we need the ASP.NET Core NewtonsoftJson for input and output format parameters.
In the solution explorer, Right-click on the project and select the Manage NuGet Packages where you can find those packages in the browse section. See the below picture.

Add the Model Class

Right-click on the solution project in the solution explorer, from the popup menu, select Add > New Folder. Name the folder as Models. Add the following classes into the Models folder: we use the POCOs (Plain Old CLR Object) class to represent Employee Model.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  6. namespace OData_API.Models  
  7. {  
  8.     public class EmployeeModel  
  9.     {  
  10.         public int   Id { get; set; }  
  11.         public string Name { get; set; }  
  12.         public string Role { get; set; }  
  13.         public string City { get; set; }  
  14.         public int  Pincode { get; set; }  
  15.     }  
  16. }  

Create a Business Logic for Employee Service

Right-click on the solution project in the solution explorer, from the popup menu, select Add > New Folder. Name the folder as Services. Add the EmployeeService Class in which our actual business logic comes into the picture. Since I have not used any Database operations in this project, I have added static data to fetch the values from the List  and one more method to fetch all the Details from the created list.
  1. using OData_API.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  7. namespace OData_API.Services  
  8. {  
  9.     public class EmployeeService  
  10.     {  
  11.         public List<EmployeeModel> CreateData()  
  12.         {  
  13.             List<EmployeeModel> employeeModels = new(); // C# 9 Syntax  
  15.             employeeModels.Add(new EmployeeModel { Id = 1, Name = "Jay", Role = "Developer", City = "Hyderabad", Pincode = 500072 });  
  16.             employeeModels.Add(new EmployeeModel { Id = 2, Name = "Chaitanya ", Role = "Developer", City = "Bangalore", Pincode = 500073 });  
  17.             employeeModels.Add(new EmployeeModel { Id = 3, Name = "Bobby Kalyan", Role = "Developer", City = "Chennai", Pincode = 500074 });  
  18.             employeeModels.Add(new EmployeeModel { Id = 4, Name = "Praveen", Role = "Developer", City = "Vizag", Pincode = 500075 });  
  19.             employeeModels.Add(new EmployeeModel { Id = 5, Name = "Naidu", Role = "Developer", City = "Cochin", Pincode = 500076 });  
  20.             employeeModels.Add(new EmployeeModel { Id = 6, Name = "Yateesh", Role = "Developer", City = "Tirupati", Pincode = 500077 });  
  21.             employeeModels.Add(new EmployeeModel { Id = 7, Name = "Priyanka", Role = "Developer", City = "Khammam", Pincode = 500064 });  
  22.             employeeModels.Add(new EmployeeModel { Id = 8, Name = "Jisha", Role = "QA", City = "Kurnool", Pincode = 500078 });  
  23.             employeeModels.Add(new EmployeeModel { Id = 9, Name = "Aravind", Role = "QA", City = "Anakapalli", Pincode = 500214 });  
  24.             employeeModels.Add(new EmployeeModel { Id = 10, Name = "Manikanta", Role = "QA", City = "Tuni", Pincode = 500443 });  
  25.             employeeModels.Add(new EmployeeModel { Id = 11, Name = "Chinna", Role = "QA", City = "Srikakulam", Pincode = 500534 });  
  26.             employeeModels.Add(new EmployeeModel { Id = 12, Name = "Samuel", Role = "QA", City = "Bhimavaram", Pincode = 500654 });  
  27.             employeeModels.Add(new EmployeeModel { Id = 13, Name = "John", Role = "QA", City = "Kharagpur", Pincode = 5000765 });  
  28.             employeeModels.Add(new EmployeeModel { Id = 14, Name = "Edward", Role = "QA", City = "Mumbai", Pincode = 5000224 });  
  29.             employeeModels.Add(new EmployeeModel { Id = 15, Name = "Nihaan", Role = "QA", City = "Mangalore", Pincode = 500965 });  
  30.             return employeeModels;  
  31.         }  
  33.         public List<EmployeeModel> GetEmployees() => CreateData().ToList();  
  34.     }  
  35. }  
So will be querying the data from that list to get the response as JSON.

Register Services through Dependency Injection (DI) and also register OData Services.

ASP.NET Core OData requires some services registered ahead to provide its functionality. The library provides an extension method called “AddOData()” to register the required OData services through the built-in dependency injection. In order to work with OData, we need the Newtonsoft Json services needs to inject into the AddControllers(). So, add the following codes into the “ConfigureServices” method in the “Startup” class,
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  4.             services.AddControllers().AddNewtonsoftJson();  
  5.             services.AddSwaggerGen(c =>  
  6.             {  
  7.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "OData_API", Version = "v1" });  
  8.             });  
  9.             services.AddScoped<EmployeeService>();  
  10.             services.AddOData();  
  11.         }  

Register the OData Endpoint

OData provides various OData capabilities to be toggled on a route and its sub-routes. We will now enable Selection, Expansion, Count, Filter, OrderBy, Top, and Skip for all routes. We have to register the OData endpoints in the startup.cs file under the configure Method to query the data.
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  2.         {  
  3.             if (env.IsDevelopment())  
  4.             {  
  5.                 app.UseDeveloperExceptionPage();  
  6.                 app.UseSwagger();  
  7.                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json""OData_API v1"));  
  8.             }  
  10.             app.UseHttpsRedirection();  
  12.             app.UseRouting();  
  14.             app.UseAuthorization();  
  16.             app.UseEndpoints(endpoints =>  
  17.             {  
  18.                 endpoints.EnableDependencyInjection();  
  19.                 endpoints.Select().Count().Filter().OrderBy().MaxTop(100).SkipToken().Expand();  
  20.                 endpoints.MapControllers();  
  22.             });  
  23.         }  
Create an empty  API Controller to implement the GET method under EmployeeController and here EnableQuery attribute enables an endpoint to have OData Capabilities.
  1. using Microsoft.AspNet.OData;  
  2. using Microsoft.AspNetCore.Http;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using OData_API.Services;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  10. namespace OData_API.Controllers  
  11. {  
  12.     //[Route("api/[controller]")]  
  13.     [ApiController]  
  14.     public class EmployeeController : ControllerBase  
  15.     {  
  16.         private readonly EmployeeService _employeeService;  
  18.         public EmployeeController(EmployeeService employeeService)  
  19.         {  
  20.             _employeeService = employeeService;  
  21.         }  
  23.         [HttpGet(nameof(GetData))]  
  24.         [EnableQuery]  
  25.         public IActionResult GetData() => Ok(_employeeService.GetEmployees());  
  26.     }  
  27. }  
Let's run the code and test with Postman
Standard Filter Operators 
Operator Description Example
Comparison Operators
eq Equal $filter=revenue eq 100000
ne Not Equal $filter=revenue ne 100000
gt Greater than $filter=revenue gt 100000
ge Greater than or equal $filter=revenue ge 100000
lt Less than $filter=revenue lt 100000
le Less than or equal $filter=revenue le 100000
Logical Operators
and Logical and $filter=revenue lt 100000 and revenue gt 2000
or Logical or $filter=contains(name,'(sample)') or contains(name,'test')
not Logical not $filter=not contains(name,'sample')
Grouping Operators
() Precedence grouping (contains(name,'sample') or contains(name,'test')) and revenue gt 5000
Standard query functions

The web API supports these standard OData string query functions.
Function Example
contains $filter=contains(name,'(sample)')
endswith $filter=endswith(name,'Inc.')
startswith $filter=startswith(name,'a')
$filter - startswith
You can create paging enabled endpoint which means if you have a lot of data on a database, and the requirement is that client needs to show the data like 10 records per page. So it is advisable that the server itself should send those 10 records per request so that the entire data payload does not travel on the network. This may also improve the performance of your services.

Let’s suppose you have 10000 records on the database, so you can enable your endpoint to return 10 records and entertain the request for the initial record and number of records to be sent. In this case, the client will make a request every time for next set of records fetch pagination option is used or the user navigates to the next page. To enable paging, just mention the page count at the [Queryable] attribute. 
For e.g. [Queryable(PageSize = 5)] 
Need to add the pagesize in the attribute
  1. [HttpGet(nameof(GetData))]  
  2.         [EnableQuery(PageSize =5)]  
  3.         public IActionResult GetData() => Ok(_employeeService.GetEmployees());  
Query Options Constraints
You can put constraints over your query options too. Suppose you do not want the client to access filtering options or skip options, then at the action level you can put constraints to ignore that kind of API request. Query Option constraints are of four types,



[EnableQuery(AllowedQueryOptions =AllowedQueryOptions.Filter | AllowedQueryOptions.OrderBy)]

Above example of the query option states that only $filter and $orderby queries are allowed on the API. 
  1. [HttpGet(nameof(GetData))]  
  2.         [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Filter | AllowedQueryOptions.OrderBy)]  
  3.         public IActionResult GetData() => Ok(_employeeService.GetEmployees());  

Example:[Queryable(AllowedLogicalOperators = AllowedLogicalOperators.GreaterThan)]

In the above-mentioned example, the statement states that only greaterThan i.e. “gt” logical operator is allowed in the query, and query options with any other logical operator other than “gt” will return an error. You can try it in your application.



[Queryable(AllowedArithmeticOperators = AllowedArithmeticOperators.Add)]

In the above-mentioned example, the statement states that only Add arithmetic operator is allowed while API call. You can try it in your application. 


I hope this article gives you a clear picture of implementing the OData in .Net 5 and all its functionalities. Download Source Code - GitHub
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
Keep learning....!