There are quite a lot of tutorials showing how to create OData services using Web API OData, but these requires Entity Framework and a database server behind. If you want a quick try or you have your own way of implementing data sources, these tutorials may not be the best fit. In this article, we will show how to build an OData service using in-memory dataas data source and with basic function.
Create the solution
Create a new solution following File -> New -> Project -> Web, then choose
ASP.NET Web Application
. Name it with Demo
. Then in the upcoming dialogue box, choose Empty
and check Web API
, click OK.Install NuGet packages
Run the following command in the Package Manager Console.
PM> Install-Package Microsoft.AspNet.OData
Add Models
In this getting-started example, we just add two model class
Person.cs
and Trip.cs
under folder Models
. Person
can navigate to Trips
.
The attributes
[Key]
and [Required]
are all from System.ComponentModel.DataAnnotations
meaning the property is key and required seperately.In-Memory data source
This tutorial uses in-memory data source, which is more flexible. Below are only one way to implement, you can definitely have your only way.
Add a folder
DataSource
and add a class file DemoDataSources.cs
with the code below.Add Controllers
Since there are two entity set, we will add two controller class under the folder
Controllers
First is controller for People
Then is the controller for Trips
In this very simple implementation, only simple
Get
with query options are allowed. If you want to enable more capabilities in your controller, the code is quite similar with what's done with EF as data source. Please refer to ASP.NET Web API OData V4 Samples and Create an OData v4 Endpoint Using ASP.NET Web API 2.2.Configure the Endpoint
The last step is to modify the
WebApiConfig.cs
file under App_Start
.Try with it
It's done to create a very basic OData endpoint with in-memory data source using Web API OData. You can try it out now! All samples below are all
GET
method.
Service document
http://localhost:[portNumber]/
Service metadata
http://localhost:[portNumber]/$metadata
Get People
http://localhost:[portNumber]/People
Queries
http://localhost:[portNumber]/People?$filter=contains(Description,'Lorem')
http://localhost:[portNumber]/People?$select=Name
http://localhost:[portNumber]/People?$expand=Trips
Wonderful information. Good to know this valuable article.
ReplyDeletevoyance serieuse gratuite mail