Skip to footer content
.NET HELP

OData C# (How It Works For Developers)

The Open Data Protocol (OData) simplifies building and consuming RESTful APIs in Microsoft .NET development. It offers a standardized approach to querying and manipulating data through familiar CRUD (Create, Read, Update, Delete) operations. This article explores how Open Data Protocol streamlines API development in .NET, providing examples and highlighting its key benefits. To explore more about OData, you can check the OData C# GitHub Repository for the source code.

OData C# (How It Works For Developers): Figure 1 - OData C#- Data access protocol

OData follows standard practices for building RESTful web APIs, using URLs and HTTP verbs like GET and POST to define operations. It represents data using an Entity Data Model (EDM) and JSON or AtomPub for message encoding. While OData simplifies API development compared to GraphQL, it may offer fewer advanced features.

OData C# (How It Works For Developers): Figure 2 - OData

Benefits of Using OData in .NET

  • Standardization: OData enforces a consistent way to define entity data models, handle requests, and format responses. This reduces development complexity and simplifies client application integration.
  • Rich Query Capabilities: OData supports a uniform way of querying data to perform CRUD operations, filtering ($filter), sorting (Ascending Order/ Descending Order)($orderby), and paging ($top,$skip) functionalities, allowing clients to retrieve specific data sets efficiently.
  • Improved Developer Experience: The .NET libraries for OData streamline API development. Developers can leverage pre-built components for routing, query handling, and data serialization, reducing code duplication and development time.
  • Interoperability: OData-compliant clients from various platforms can seamlessly interact with your .NET-based OData service, promoting broader application integration.

Getting Started with OData in the .NET Framework

The .NET libraries for OData enhance developer experience by facilitating efficient ways to manipulate data sets. It simplifies building and consuming RESTful APIs in .NET development. It offers a standardized approach to querying and manipulating data through familiar CRUD operations (Create, Read, Update, Delete).

Setting Up OData in .NET Projects

Start by opening your new project in Visual Studio. Then, navigate to the Solution Explorer, right-click on your project, and select "Manage NuGet Packages". Search for Microsoft.AspNetCore.OData and install it. The current OData version is 8.2.5.

To install OData in the NuGet Package Manager Console, use the following command.

Install-Package Microsoft.AspNetCore.OData

OData C# (How It Works For Developers): Figure 3 - Install OData

Example: Creating an OData Service in ASP.NET Core

Let's create a simple OData model class in an ASP.NET Core application. In the following code, the below class will expose a list of services that can be queried using the OData syntax.

public class Service
{
    public int Id { get; set; } 
    public string FirstName { get; set; }
    public decimal Price { get; set; }
}
public class Service
{
    public int Id { get; set; } 
    public string FirstName { get; set; }
    public decimal Price { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Description of the code

The Service class represents a basic data structure in C# for managing a service. It includes three properties: Id: An integer identifier for the service. FirstName: A string representing the first name associated with the service. Price: A decimal value indicating the price of the service. This class can be used as a building block for creating more complex service-related functionality in .NET development. We may also use collection or navigation properties based on the scenario.

Here's how you can set up an OData controller in an ASP.NET Core application in Visual Studio to expose a list of services via a standardized OData endpoint. The following example demonstrates a basic implementation using a static list of services and enabling OData query functionalities in Web API:

using DemoOData.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;

namespace DemoOData.Controllers
{
    [Route("odata/[controller]")]
    public class ServiceController : ODataController
    {
        private static readonly List<Service> Products = new List<Service>
        {
            new Service { Id = 1, FirstName = "Laptop", Price = 6239.9M },
            new Service { Id = 2, FirstName = "Smartphone", Price = 2585.9M }
        };

        [HttpGet]
        [EnableQuery]
        public IActionResult Get() => Ok(Products);
    }
}
using DemoOData.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;

namespace DemoOData.Controllers
{
    [Route("odata/[controller]")]
    public class ServiceController : ODataController
    {
        private static readonly List<Service> Products = new List<Service>
        {
            new Service { Id = 1, FirstName = "Laptop", Price = 6239.9M },
            new Service { Id = 2, FirstName = "Smartphone", Price = 2585.9M }
        };

        [HttpGet]
        [EnableQuery]
        public IActionResult Get() => Ok(Products);
    }
}
Imports DemoOData.Models
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.OData.Query
Imports Microsoft.AspNetCore.OData.Routing.Controllers

Namespace DemoOData.Controllers
	<Route("odata/[controller]")>
	Public Class ServiceController
		Inherits ODataController

		Private Shared ReadOnly Products As New List(Of Service) From {
			New Service With {
				.Id = 1,
				.FirstName = "Laptop",
				.Price = 6239.9D
			},
			New Service With {
				.Id = 2,
				.FirstName = "Smartphone",
				.Price = 2585.9D
			}
		}

		<HttpGet>
		<EnableQuery>
		Public Function [Get]() As IActionResult
			Return Ok(Products)
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Description of the code

The provided code defines an ODataController named ServiceController in an ASP.NET Core application, enabling querying and manipulating data using the OData protocol. It routes requests to odata/Service and serves a static list of Service objects, including a laptop and a smartphone. The Get method, decorated with [EnableQuery], allows clients to perform OData queries (filtering, sorting, paging) on the Products list, returning the results as an IActionResult for HTTP GET requests.

Register OData Services in the Program.cs

To integrate OData into a .NET 6 application, we need to install and configure the necessary OData packages. This involves defining the OData model, setting up the OData middleware, and configuring services to support OData features such as filtering, ordering, and expansion.

using DemoOData.Models;
using Microsoft.AspNetCore.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

static IEdmModel GetEdmModel()
{
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<Service>("Services");
    return builder.GetEdmModel();
}

builder.Services.AddControllers()
    .AddOData(options => options
        .AddRouteComponents("odata", GetEdmModel())
        .Select()
        .Filter()
        .OrderBy()
        .SetMaxTop(20)
        .Count()
        .Expand()
    );
using DemoOData.Models;
using Microsoft.AspNetCore.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

static IEdmModel GetEdmModel()
{
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<Service>("Services");
    return builder.GetEdmModel();
}

builder.Services.AddControllers()
    .AddOData(options => options
        .AddRouteComponents("odata", GetEdmModel())
        .Select()
        .Filter()
        .OrderBy()
        .SetMaxTop(20)
        .Count()
        .Expand()
    );
Imports DemoOData.Models
Imports Microsoft.AspNetCore.OData
Imports Microsoft.OData.Edm
Imports Microsoft.OData.ModelBuilder

Private builder = WebApplication.CreateBuilder(args)

' Add services to the container.
builder.Services.AddControllers()
' Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static IEdmModel GetEdmModel()
'{
'	ODataConventionModelBuilder builder = New ODataConventionModelBuilder();
'	builder.EntitySet<Service>("Services");
'	Return builder.GetEdmModel();
'}

builder.Services.AddControllers().AddOData(Function(options) options.AddRouteComponents("odata", GetEdmModel()).Select().Filter().OrderBy().SetMaxTop(20).Count().Expand())
$vbLabelText   $csharpLabel

Description of the code

This code configures OData support in a .NET 6 application. First, it imports necessary namespaces and creates a WebApplicationBuilder instance. The GetEdmModel method defines the OData model using the ODataConventionModelBuilder, which specifies an entity set for Service entities. The AddOData method is then called to configure OData services, including enabling select, filter, order by, count, expand, and setting a maximum top value of 20 for query results. This setup ensures the application can handle OData queries effectively.

The AddOData() method employs the GetEdmModel() method, which retrieves the data model used for querying, forming the foundation of an OData service. This service utilizes an abstract data model known as Entity Data Model (EDM) to define the exposed data. The ODataConventionModelBuilder class generates an EDM through default naming conventions, minimizing code requirements. Alternatively, developers can utilize the ODataModelBuilder class for greater control over the EDM.

Screenshot of the code

OData C# (How It Works For Developers): Figure 4 - Code in Visual Studio

Running the Service

After running the service, you can query the Service using various OData query options, such as:

https://localhost:7131/odata/Service

Output of the Program

OData C# (How It Works For Developers): Figure 5 - OData Service Output

Introduction to IronPDF

IronPDF is a comprehensive C# library designed to simplify the conversion of files to PDF, splitting of PDF pages, and removal of pages from PDF within .NET applications. It offers a wide range of features, including the ability to generate PDFs from HTML, CSS, images, and JavaScript, enabling developers to effortlessly transform web content into high-quality PDF documents. With its intuitive API and powerful rendering engine, IronPDF empowers developers to streamline PDF generation processes, facilitating the integration of dynamic document generation capabilities into their applications with ease.

OData C# (How It Works For Developers): Figure 6 - IronPDF

Adding IronPDF to Project

To install IronPDF in Visual Studio, navigate to NuGet Package Manager Console, and use the following command.

Install-Package IronPdf

Generating PDF

To generate a PDF document from HTML content in a .NET application, we can use the ChromePdfRenderer class from a library like DinkToPdf or similar. This example demonstrates how to create a PDF with details of an Employee record.

public record Employee (string FirstName, string LastName);

class Program
{
    static void Main(string[] args)
    {
        var employee = new Employee("Iron", "Developer");
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {employee.FirstName} {employee.LastName}</p>");
        pdf.SaveAs("PersonRecord.pdf");
    }
}
public record Employee (string FirstName, string LastName);

class Program
{
    static void Main(string[] args)
    {
        var employee = new Employee("Iron", "Developer");
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {employee.FirstName} {employee.LastName}</p>");
        pdf.SaveAs("PersonRecord.pdf");
    }
}
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record Employee(string FirstName, string LastName)

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim employee As New Employee("Iron", "Developer")
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf($"<h1>Person Record</h1><p>Name: {employee.FirstName} {employee.LastName}</p>")
		pdf.SaveAs("PersonRecord.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

This example creates a simple Employee record and then uses IronPDF to generate a PDF document displaying the person's name. It showcases how seamlessly C# records can integrate with PDF generation in .NET applications.

OData C# (How It Works For Developers): Figure 7 - PDF Output

Conclusion

OData simplifies the development and consumption of RESTful APIs in .NET by providing standardized querying and manipulation capabilities. We can also integrate it with Entity Framework, enhancing development efficiency by simplifying data access and management. OData streamlines API development, enabling seamless integration and interoperability across various platforms with its rich query functionalities and improved developer experience. Additionally, IronPDF offers comprehensive features and support for robust PDF manipulation within .NET applications.

Frequently Asked Questions

What is OData in the context of .NET development?

OData, or Open Data Protocol, simplifies building and consuming RESTful APIs in .NET by providing a standardized approach to querying and manipulating data through CRUD operations.

What are the benefits of using OData in .NET?

OData offers standardization, rich query capabilities, improved developer experience, and interoperability. It reduces development complexity, allows efficient data retrieval, streamlines API development, and promotes broader application integration.

How can I set up OData in a .NET project?

To set up OData in a .NET project, you can use Visual Studio to manage NuGet packages, search for Microsoft.AspNetCore.OData, and install it. Then, configure OData services in your project by defining the OData model and setting up the middleware.

What is the purpose of the ODataConventionModelBuilder in .NET?

ODataConventionModelBuilder is used to generate an Entity Data Model (EDM) using default naming conventions, minimizing code requirements for defining the OData model in .NET applications.

How does OData improve developer experience in .NET?

OData improves developer experience by providing pre-built components for routing, query handling, and data serialization, reducing code duplication, and development time.

What is a comprehensive library for PDF manipulation in .NET?

IronPDF is a C# library that simplifies the conversion of files to PDF, splitting and removal of PDF pages, and generation of PDFs from HTML. It is used in .NET applications to streamline PDF generation processes.

How can I generate a PDF from HTML content in .NET using a library?

Using IronPDF, you can generate a PDF by creating an HTML string and using the ChromePdfRenderer class to render it as a PDF document, which can be saved to a file.

What is the purpose of the EnableQuery attribute in OData?

The EnableQuery attribute in OData allows clients to perform OData queries such as filtering, sorting, and paging on the data exposed by an OData controller.

What are CRUD operations in the context of OData?

CRUD operations in OData refer to the standard operations of Create, Read, Update, and Delete, which are used to manipulate data in RESTful APIs.

How does OData promote interoperability?

OData promotes interoperability by allowing OData-compliant clients from various platforms to seamlessly interact with .NET-based OData services, enabling broader application integration.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.