Skip to content

Commit 49e197f

Browse files
Add odata tutorial
1 parent ab943f9 commit 49e197f

File tree

3 files changed

+264
-0
lines changed

3 files changed

+264
-0
lines changed

source/fundamentals.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Fundamentals
3030
/fundamentals/time-series
3131
/fundamentals/encrypt-fields
3232
/fundamentals/geo
33+
/fundamentals/odata
3334

3435
- :ref:`Connecting to MongoDB <csharp-connection>`
3536
- :ref:`csharp-db-coll`
@@ -50,3 +51,4 @@ Fundamentals
5051
- :ref:`csharp-time-series`
5152
- :ref:`Encrypt Fields <csharp-fle>`
5253
- :ref:`csharp-geo`
54+
- :ref:`csharp-odata`
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
.. _csharp-odata:
2+
3+
======================
4+
Use OData with MongoDB
5+
======================
6+
7+
.. facet::
8+
:name: genre
9+
:values: tutorial
10+
11+
.. meta::
12+
:keywords: asp.net, integration, code example, enable query
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
OData (Open Data Protocol) is an open protocol that allows the creation and
24+
consumption of queryable and interoperable RESTful APIs in a simple and standard
25+
way. It is a set of best practices for building and consuming RESTful APIs.
26+
27+
In this tutorial, you will learn how to integrate OData with your MongoDB application.
28+
29+
Sample Data
30+
~~~~~~~~~~~
31+
32+
This tutorial uses the ``sample_restaurants.restaurants`` collection
33+
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
34+
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`.
35+
36+
Tutorial
37+
--------
38+
39+
.. procedure::
40+
41+
.. step:: Install Dependencies
42+
43+
Create a new ASP.Net application named
44+
``ODataExample`` and install the {+driver-short+}. You can install the
45+
driver by using the NuGet package manager in your IDE, or by running the
46+
following command in the .NET CLI:
47+
48+
.. code-block:: shell
49+
50+
dotnet add package MongoDB.Driver
51+
52+
Then, install the ``MongoDB.AspNetCore.OData`` NuGet
53+
package through the NuGet Package Manager or through the .NET CLI by running the
54+
following command:
55+
56+
.. code-block:: shell
57+
58+
dotnet add package MongoDB.AspNetCore.OData
59+
60+
.. step:: Define your Models
61+
62+
Create a new folder in your solution called ``Models`` and copy the
63+
following ``Restaurant.cs``, ``Address.cs``, and ``GradeEntry.cs`` files into the
64+
folder:
65+
66+
.. literalinclude:: /includes/code-examples/Restaurant.cs
67+
:language: csharp
68+
:copyable:
69+
:dedent:
70+
71+
.. literalinclude:: /includes/code-examples/Address.cs
72+
:language: csharp
73+
:copyable:
74+
:dedent:
75+
76+
.. literalinclude:: /includes/code-examples/GradeEntry.cs
77+
:language: csharp
78+
:copyable:
79+
:dedent:
80+
81+
.. include:: /includes/convention-pack-note.rst
82+
83+
.. step:: Create an OData Controller
84+
85+
Create a new folder in your solution called ``Controllers`` and add a new
86+
controller file called ``RestaurantsController.cs``. Copy the following code
87+
into the file:
88+
89+
.. literalinclude:: /includes/fundamentals/code-examples/connection/odata.cs
90+
:language: csharp
91+
:start-after: // start-controller
92+
:end-before: // end-controller
93+
94+
This code performs the following actions:
95+
96+
- Creates a constructor that connects to MongoDB, and gets the
97+
``restaurants`` collection.
98+
- Creates a ``Get`` endpoint that returns all restaurants in the collection.
99+
- Specifies the ``MongoEnableQuery`` attribute to enable querying on the
100+
``Get`` endpoint.
101+
- Specifies the ``PageSize`` attribute on ``MongoEnableQuery`` to limit the
102+
number of documents returned to ``5``.
103+
104+
.. step:: Configure the OData Service
105+
106+
In your ``Program.cs`` file, add the following code to configure the OData
107+
service and map your controller endpoints.
108+
109+
.. literalinclude:: /includes/fundamentals/code-examples/connection/odata.cs
110+
:language: csharp
111+
:start-after: // start-configure
112+
:end-before: // end-configure
113+
114+
.. note::
115+
116+
Replace the ``<"Your connection URI">`` placeholder with your MongoDB connection string.
117+
118+
This code performs the following actions:
119+
120+
- Instantiates a new ``MongoClient`` and passes it to the controller
121+
- Defines the Entity Data Model (EDM) and registers ``Restaurants`` as an
122+
entity set with the key, ``Id``.
123+
- Adds the OData service and enables the ``Select()`` query capability.
124+
- Registers the route by using the ``AddRouteComponents()`` method.
125+
- Calls the ``UseRouting()`` and ``MapControllers()`` methods to match
126+
incoming HTTP requests and route them to the appropriate endpoint.
127+
128+
.. step:: Run the Application
129+
130+
Run the application by using your IDE, or by running the following command
131+
in your shell at the route directory of your project:
132+
133+
.. code-block:: shell
134+
135+
dotnet run ODataExample.csproj
136+
137+
After running the application, your terminal should display output similar
138+
to the following:
139+
140+
.. code-block:: none
141+
142+
info: Microsoft.Hosting.Lifetime[14]
143+
Now listening on: http://localhost:5183
144+
info: Microsoft.Hosting.Lifetime[0]
145+
Application started. Press Ctrl+C to shut down.
146+
info: Microsoft.Hosting.Lifetime[0]
147+
Hosting environment: Development
148+
info: Microsoft.Hosting.Lifetime[0]
149+
Content root path: /Users/jordan.smith/Documents/mongo/ODataTest/ODataTest
150+
151+
.. tip::
152+
153+
After running your application, your IDE might automatically open a
154+
browser window to the URL where the application is running, which
155+
displays a ``page can't be found`` error. This is expected because the
156+
application only has a single ``Get`` endpoint configured.
157+
158+
.. step:: Query the Data
159+
160+
To query the data, navigate to the ``Get`` endpoint specified in the
161+
application. To do so, open a browser and navigate to the ``localhost``
162+
URL specified in the terminal output from the preceding step. Then, append
163+
the route for the ``Get`` endpoint: ``/odata/Restaurants``. For example, if an
164+
application is running at ``localhost:5183``, navigate to
165+
``http://localhost:5183/odata/Restaurants``.
166+
167+
If successful, the browser displays 5 restaurants in the
168+
collection, in JSON format. The output should look similar to the
169+
following:
170+
171+
.. code-block:: json
172+
173+
{
174+
"@odata.context": "http://localhost:5183/odata/$metadata#Restaurants",
175+
"value": [
176+
{
177+
"Name": "Glorious Food",
178+
"RestaurantId": "40361521",
179+
"Cuisine": "American",
180+
"Borough": "Manhattan",
181+
"Id": "...",
182+
"Address": {
183+
"Building": "522",
184+
"Coordinates": [-73.95171, 40.767461],
185+
"Street": "East 74 Street",
186+
"ZipCode": "10021"
187+
},
188+
"Grades": [
189+
...
190+
]
191+
},
192+
193+
...
194+
195+
]
196+
}
197+
198+
Additional Information
199+
----------------------
200+
201+
To learn more about ASP.NET Core OData, see the `Microsoft OData documentation
202+
<https://learn.microsoft.com/en-us/odata/webapi-8/overview>`__.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// start-controller
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.AspNetCore.OData.Routing.Controllers;
4+
using MongoDB.AspNetCore.OData;
5+
using MongoDB.Driver;
6+
using ODataTest.Models;
7+
8+
namespace ODataTest.Controllers;
9+
10+
public class RestaurantsController : ODataController
11+
{
12+
private readonly IQueryable<Restaurant> _restaurants;
13+
14+
public RestaurantsController(IMongoClient client)
15+
{
16+
var database = client.GetDatabase("sample_restaurants");
17+
_restaurants = database.GetCollection<Restaurant>("restaurants").AsQueryable();
18+
}
19+
20+
// Register Get endpoint and set max documents to 5
21+
[MongoEnableQuery(PageSize = 5)]
22+
public ActionResult<IEnumerable<Restaurant>> Get()
23+
{
24+
var restaurantList = _restaurants.Take(5);
25+
return Ok(restaurantList);
26+
}
27+
}
28+
// end-controller
29+
30+
// start-configure
31+
using Microsoft.AspNetCore.OData;
32+
using Microsoft.OData.ModelBuilder;
33+
using MongoDB.Bson.Serialization.Conventions;
34+
using MongoDB.Driver;
35+
using ODataTest.Models;
36+
37+
var builder = WebApplication.CreateBuilder(args);
38+
39+
// Register a convention pack to convert fields to camel case
40+
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
41+
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
42+
43+
builder.Services.AddSingleton<IMongoClient>(new MongoClient("Your connection URI"));
44+
45+
// Register the Restaurants entity and set the Id field as the key
46+
var modelBuilder = new ODataConventionModelBuilder();
47+
modelBuilder.EntitySet<Restaurant>("Restaurants");
48+
modelBuilder.EntityType<Restaurant>().HasKey(r => r.Id);
49+
50+
// Add OData and specify query capabilities
51+
builder.Services.AddControllers().AddOData(
52+
options => options.Select().AddRouteComponents("odata", modelBuilder.GetEdmModel())
53+
);
54+
55+
var app = builder.Build();
56+
app.UseRouting();
57+
app.MapControllers();
58+
59+
app.Run();
60+
// end-configure

0 commit comments

Comments
 (0)