Getting Started with ASP.NET Core OData 8 - OData (2024)

  • Article

Applies To:# OData Web API 8 supportedGetting Started with ASP.NET Core OData 8 - OData (1) OData Web API v8

This tutorial shows how to create and run an ASP.NET Core OData 8 application

You'll learn how to:
✅ Create an ASP.NET Core application
✅ Add Microsoft.AspNetCore.OData library package
✅ Define the CLR types
✅ Add an OData controller
✅ Build the Edm model and configure the service
✅ Run the OData service
✅ Interact with the OData service from an API client

Prerequisites

  • .NET 6.0
  • .NET Core 3.1

Visual Studio 2022 with the ASP.NET and web development workload

Create an ASP.NET Core application

  • Visual Studio 2022
  • Visual Studio 2019
  • Start Visual Studio 2022 and select Create a new project.

  • In the Create a new project dialog:

  • Name the project Lab01 and select Next.

  • In the Additional information dialog:

    • Select .NET 6.0 (Long Term Support).
    • Uncheck Configure for HTTPS checkbox.
    • Select Create.

    Getting Started with ASP.NET Core OData 8 - OData (3)

Add Microsoft.AspNetCore.OData library package

Install the Microsoft.AspNetCore.OData 8.x Nuget package:

  • Visual Studio
  • .NET Core CLI

In the Visual Studio Package Manager Console:

Install-Package Microsoft.AspNetCore.OData

Define the CLR types

Add a folder named Models to the project and then add the following C# classes.

Order class

namespace Lab01.Models{ public class Order { public int Id { get; set; } public decimal Amount { get; set; } }}

Customer class

namespace Lab01.Models{ using System.Collections.Generic; public class Customer { public int Id { get; set; } public string Name { get; set; } public List<Order> Orders { get; set; } }}

The Order and Customer classes both contain an Id property that is conventionally treated as the key property of the entity. Note also that the Customer class has a collection property named Orders of type List<Order>.

Add an OData controller

Add a folder named Controllers and then add the following C# class.

namespace Lab01.Controllers{ using System; using System.Collections.Generic; using System.Linq; using Lab01.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OData.Query; using Microsoft.AspNetCore.OData.Routing.Controllers; public class CustomersController : ODataController { private static Random random = new Random(); private static List<Customer> customers = new List<Customer>( Enumerable.Range(1, 3).Select(idx => new Customer { Id = idx, Name = $"Customer {idx}", Orders = new List<Order>( Enumerable.Range(1, 2).Select(dx => new Order { Id = (idx - 1) * 2 + dx, Amount = random.Next(1, 9) * 10 })) })); [EnableQuery] public ActionResult<IEnumerable<Customer>> Get() { return Ok(customers); } [EnableQuery] public ActionResult<Customer> Get([FromRoute] int key) { var item = customers.SingleOrDefault(d => d.Id.Equals(key)); if (item == null) { return NotFound(); } return Ok(item); } }}

In the controller, we define a Customer collection (List<Customer>) and initialize it with 3 Customer objects. This will serve as our in-memory data source for the OData service.

We also define two overloads of the Get method. The first overload does not accept any arguments while the second one accepts a single integer argument. In addition, the first overload returns a collection of Customer objects while the second one returns a single Customer object. These two methods will handle HTTP GET requests from the client. Both overloads are decorated with the EnableQuery attribute. This attribute is responsible for applying the query options that are passed in the query string.

Build the Edm model and configure the service

  • .NET 6.0
  • .NET Core 3.1
// Program.csusing Lab01.Models;using Microsoft.AspNetCore.OData;using Microsoft.OData.ModelBuilder;var builder = WebApplication.CreateBuilder(args);var modelBuilder = new ODataConventionModelBuilder();modelBuilder.EntityType<Order>();modelBuilder.EntitySet<Customer>("Customers");builder.Services.AddControllers().AddOData( options => options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(null).AddRouteComponents( "odata", modelBuilder.GetEdmModel()));var app = builder.Build();app.UseRouting();app.UseEndpoints(endpoints => endpoints.MapControllers());app.Run();

In the preceding code block, we define the Edm model. As part of the model, we register Order as an entity type and Customers as an entity set - Customer entity type also gets registered as a result. In this case, the ODataConventionalModelBuilder is being used to build the Edm model.

We then proceed to add essential OData services by calling the AddOData method, in the process enabling different OData query capabilities - $select, $filter, $orderby, $expand, count, $top and $skip. The AddRouteComponents method is used to register a route, passing along the Edm model to associate it with.

The final step in configuring the service is adding the two middlewares responsible for matching incoming HTTP requests and dispatching those requests to the application's executable endpoints. We do this by calling UseRouting and UseEndpoints - the former adds route matching to the middleware pipeline while the latter adds endpoint execution.

Run the OData service

Before running the service, select the debugging profile named after the project - Lab01 - to use ASP.NET Core Kestrel web server.

Getting Started with ASP.NET Core OData 8 - OData (4)

Press F5 to build and run the application.

The following window will be displayed:

Getting Started with ASP.NET Core OData 8 - OData (5)

Take note of the endpoint that the application is listening on - http://localhost:5000. The port might differ depending on the version of Visual Studio and other environmental settings.

Interact with the OData service from an API client

You can use any API client of your choice to interact with the OData service.

Below is a list of endpoints exposed by the OData service created in this tutorial:

MethodEndpointDescriptionResponse
GET/odataRetrieve service documentJSON-based respresentation of the service document listing all the top-level feeds / entity sets
GET/odata/$metadataRetrieve service metadataService metadata document describing the Entity Data Model (EDM) for the service
GET/odata/CustomersRetrieve all customersCollection of customers
GET/odata/Customers/$countRetrieve number of customersNumber of customers
GET/odata/Customers({key})Retrieve customer by IDCustomer object
GET/odata/Customers/{key}Retrieve customer by IDCustomer object

Query service metadata

To query service metadata, send a GET request to the service metadata endpoint - /odata/$metadata

Request
GET http://localhost:5000/odata/$metadata
Response
<?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"> <edmx:DataServices> <Schema Namespace="Lab01.Models" xmlns="http://docs.oasis-open.org/odata/ns/edm"> <EntityType Name="Order"> <Key> <PropertyRef Name="Id" /> </Key> <Property Name="Id" Type="Edm.Int32" Nullable="false" /> <Property Name="Amount" Type="Edm.Decimal" Nullable="false" Scale="Variable" /> </EntityType> <EntityType Name="Customer"> <Key> <PropertyRef Name="Id" /> </Key> <Property Name="Id" Type="Edm.Int32" Nullable="false" /> <Property Name="Name" Type="Edm.String" /> <NavigationProperty Name="Orders" Type="Collection(Lab01.Models.Order)" /> </EntityType> </Schema> <Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm"> <EntityContainer Name="Container"> <EntitySet Name="Customers" EntityType="Lab01.Models.Customer" /> </EntityContainer> </Schema> </edmx:DataServices></edmx:Edmx>

Notice the Order and Customer entity types as well as the Customers entity set - nested within the EntityContainer element. Notice also the Property and NavigationProperty elements used to define the structure of the schema types.

Querying service data

The query capabilities offered by OData are immense. Covering all supported capabilities is beyond the scope of this tutorial. Let's take a look at a few:

Example 1: Retrieve all customers

To retrieve all customers, use the following query:

Request
GET http://localhost:5000/odata/Customers
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers", "value": [ { "Id": 1, "Name": "Customer 1" }, { "Id": 2, "Name": "Customer 2" }, { "Id": 3, "Name": "Customer 3" } ]}

NOTE: When you query an entity or entity collection, the default response does not include any related entities or entity collections. The response above does not include the Orders collection, even though the Customer entity has an Orders navigation property.

Example 2: Retrieve customer entity by key

Entities are required to define a key property. In the case of the Customer entity, the Id property is conventionally designated as the key property - on account of the naming.

To retrieve a customer with a key value of 2, use the following query:

Request
GET http://localhost:5000/odata/Customers(2)
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers/$entity", "Id": 2, "Name": "Customer 2"}

Example 3: Retrieve customers with Id equal to 1 or 3

By using the $filter query option, you can specify the expressions to be used to limit the results to be returned.

To retrieve customers with Id equal to 1 or 3, use the following query:

Request
GET http://localhost:5000/odata/Customers?$filter=Id eq 1 or Id eq 3
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers", "value": [ { "Id": 1, "Name": "Customer 1" }, { "Id": 3, "Name": "Customer 3" } ]}

Example 4: Retrieve customers ordered by Id in descending order

By using the $orderby query option, you can specify a custom sort order for the returned results - either ascending order using asc or descending order using desc. The $orderby query option takes a comma-separated list of sort columns together with the corresponding sort order. A missing sort order implies ascending order.

To retrieve all the customers ordered by Id in descending order, use the following query:

Request
GET http://localhost:5000/odata/Customers?$orderby=Id desc
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers", "value": [ { "Id": 3, "Name": "Customer 3" }, { "Id": 2, "Name": "Customer 2" }, { "Id": 1, "Name": "Customer 1" } ]}

Example 5: Retrieve customer with Id equal to 2 and expand their list of orders

By using the $expand query option, you can include related entities or entity collections in the response. The $expand option takes a comma-separated list of navigation properties to expand.

To include all the orders for a particular customer, use the following query:

Request
GET http://localhost:5000/odata/Customers(2)?$expand=Orders
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers(Orders())/$entity", "Id": 2, "Name": "Customer 2", "Orders": [ { "Id": 3, "Amount": 20 }, { "Id": 4, "Amount": 20 } ]}

Example 6: Retrieve customer names only

By using the $select query option, you can specify a subset of properties to be included in the response. The $select query option takes a comma-separated list of properties to be returned.

To retrieve only the name of each customer, use the following query:

Request
GET http://localhost:5000/odata/Customers?$select=Name
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers(Name)", "value": [ { "Name": "Customer 1" }, { "Name": "Customer 2" }, { "Name": "Customer 3" } ]}

Example 7: Combine multiple query options together

To retrieve names of top 2 customers ordered by Id in descending order and expand their list of orders, use the following query:

Request
GET http://localhost:5000/odata/Customers?$orderby=Id desc&$expand=Orders&$top=2&select=Name
Response
{ "@odata.context": "http://localhost:5000/odata/$metadata#Customers(Name,Orders())", "value": [ { "Name": "Customer 3", "Orders": [ { "Id": 5, "Amount": 10 }, { "Id": 6, "Amount": 80 } ] }, { "Name": "Customer 2", "Orders": [ { "Id": 3, "Amount": 20 }, { "Id": 4, "Amount": 20 } ] } ]}
Getting Started with ASP.NET Core OData 8 - OData (2024)

FAQs

How to create OData service in asp net core? ›

Install the packages
  1. In Visual Studio go to Nuget Package Manager and install Microsoft. AspNetCore. OData.
  2. In VS code, go to terminal and execute dotnet add package Microsoft. AspNetCore. OData to add OData packages in a project.
Jan 26, 2022

What is routing in asp net core OData 8? ›

In ASP.NET Core OData 8, an endpoint represents the controller action that the incoming request resolves to, along with other metadata attached to the route that matches the request. Routing uses a pair of middleware, registered by UseRouting and UseEndpoints : UseRouting adds route matching to the middleware pipeline.

How does OData work in .NET core? ›

OData follows common practices for building RESTful web services. For instance, it uses URLs to identify resources and HTTP verbs like GET, POST, etc. to define operations on them. Data exposed by the OData service is described by an Entity Data Model (EDM), while JSON or AtomPub are used for message encoding.

What is Microsoft AspNetCore OData? ›

ASP.NET Core OData is a . NET library for building REST API services that conform to the OData protocol.

What is the difference between OData and rest? ›

OData and REST are related but distinct concepts. REST is an architectural style for building web APIs, while OData builds upon REST to define best practices for building RESTful APIs. OData provides additional features such as enhanced query capabilities and standardized metadata.

How to create OData service in C#? ›

In this article
  1. a. Create the Visual Studio project. In Visual Studio, create a new C# project from the ASP.NET Web Application template. ...
  2. b. Install the OData packages. In the NuGet Package Manager, install Microsoft. ...
  3. c. Add a model class. ...
  4. d. Add a controller class. ...
  5. e. Configure the OData Endpoint. ...
  6. f. Start the OData service.
Dec 8, 2022

How to configure routing in asp net core? ›

Inside the ConfigureRoute method, you can configure your routes; you can see that this method has to take a parameter of type IRouteBuilder. The goal of routing is to describe the rules that ASP.NET Core MVC will use to process an HTTP request and find a controller that can respond to that request.

What are the 3 types of routing performed by BGP? ›

Types of BGP and uses
  • Exterior BGP. Exterior BGP is used for exchanging routing information between autonomous systems. ...
  • Interior BGP. Internal BGP, or IBGP, is used when there are multiple paths egressing EGBP. ...
  • MP-BGP. Multiprotocol BGP is an IBGP that enables the distribution of address families.

What are the two types of routing supported by asp net core? ›

There are two types of routing for action methods:
  • Conventional Routing.
  • Attribute Routing.
Jan 13, 2022

What is OData for dummies? ›

The simplest definition of OData would be that it is a standardized protocol built over existing HTTP and REST protocols supporting CRUD (Create, Read, Update, Delete) operations for creating and consuming data APIs. Nickname: ODBC for the Web. 2. Entity Data Model and an OData metadata.

What is the advantage of using OData? ›

It lets developers interact with data by using RESTful web services. It provides a simple and uniform way to share data in a discoverable manner. It enables broad integration across products. It enables integration by using the HTTP protocol stack.

How do I know if OData service is activated? ›

  1. Log on to your front-end server (your SAP Gateway system).
  2. In transaction SPRO, navigate to SAP Reference IMG SAP NetWeaver SAP Gateway OData Channel Administration General Settings Activate and Maintain Services and execute the Customizing activity. ...
  3. Activate the services that are required for your application:

What is the difference between REST service and OData service? ›

In summary, while REST APIs provide a simple, lightweight way to expose CRUD operations over HTTP, OData is a more comprehensive protocol for querying and updating data, with a rich set of features for accessing and modifying data, complex types and relationships, custom operations, and more standardized querying.

What is the difference between Microsoft NET Core app and Microsoft ASP.NET Core app? ›

NET Core is an Operating System independent Platform that executes without particular runtime. Developers built dynamic applications for Desktops, Mobile applications. Cloud with ASP.NET Core is an Open-Source and Cross-Platform Framework.

How to get data from OData service? ›

OData services support requests for data via HTTP GET requests.
  1. Requesting Entity Collections.
  2. Requesting an Individual Entity by ID.
  3. Requesting an Individual Property.
  4. Requesting an Individual Property Raw Value.
Dec 8, 2022

How to create OData service in SAC? ›

Create a Model of OData Services in SAP Analytics Cloud
  1. Log into your Analytics Cloud instance and click Create -> Model from the menu.
  2. Choose "Get data from a datasource" and select "OData Services"
  3. Choose "Create a new query" and click Next.
  4. Name the Execute, select an OData endpoint (like Orders) and click Next.

How to add OData service? ›

Procedure
  1. Log on to the SAP Fiori server backend using SAP GUI.
  2. Enter transaction Activate and Maintain Services (/N/IWFND/MAINT_SERVICE).
  3. Choose Add Service.
  4. For the System Alias field, use the value help to select the correct service. ...
  5. Enter the service name in the Technical Service Name field and choose Enter.

How to create OData REST API? ›

How to Use Web API OData to Build an OData V4 Service without Entity Framework
  1. Create the solution. Create a new solution following File -> New -> Project -> Web, then choose ASP.NET Web Application . ...
  2. Install NuGet packages. ...
  3. Add Models. ...
  4. In-Memory data source. ...
  5. Add Controllers. ...
  6. Configure the Endpoint. ...
  7. Try with it.
Mar 12, 2015

How to create OData service from function module? ›

We can create OData service on RFC enabled Function module and make use of the FM functionality through service. We have created a custom RFC FM which has importing parameter VBELN and returns VBELN,AUART and LIFSK . Create SEGW project. Right click on data model ,Import >>RFC/BOR Interface.

Top Articles
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6264

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.