Overview
OData(Open Data Protocol)は、REST状 API を構築して消費するための標準化プロトコルで、 HTTPリクエストを使用してデータのクエリと操作を可能にします。 これにより、複数のソースからのデータを公開して操作する統一された方法が提供されます。
このチュートリアルでは、 OData をMongoDBアプリケーションと統合する方法を学びます。
サンプル データ
このチュートリアルでは、Atlasサンプルデータセット の sample_restaurants.restaurantsコレクションを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「 .NET/ C#ドライバーを使い始める 」を参照してください。
Tutorial
依存関係のインストール
ODataExample という名前の新しい ASP.NETアプリケーションを作成し、 .NET/ C#ドライバーをインストールします。 ドライバーをインストールするには、IDE で NuGetパッケージマネージャーを使用するか、 .NET CLI で次のコマンドを実行中。
dotnet add package MongoDB.Driver次に、次のコマンドを実行中て、NuGet パッケージ マネージャーまたは.NET CLI を使用して MongoDB.AspNetCore.OData NuGetパッケージをインストールします。
dotnet add package MongoDB.AspNetCore.ODataモデルを定義する
ソリューション内に Models という新しいフォルダーを作成し、次の Restaurant.cs、Address.cs、GradeEntry.cs ファイルをフォルダーにコピーします。
public class Restaurant{ [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")] public string RestaurantId { get; set; }
public string Cuisine { get; set; }
public Address Address { get; set; }
public string Borough { get; set; }
public List<GradeEntry> Grades { get; set; }}public class Address{ public string Building { get; set; }
[BsonElement("coord")] public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")] public string ZipCode { get; set; }}public class GradeEntry{ public DateTime Date { get; set; }
public string Grade { get; set; }
public float? Score { get; set; }}注意
restaurantsコレクションのドキュメントは、スニペット ケースの命名規則を使用します。このガイドの例では、ConventionPack を使用してコレクション内のフィールドをパスカル ケースに逆シリアル化し、Restaurantクラスのプロパティにマップします。
カスタム直列化について詳しくは、「カスタム直列化」を参照してください。
OData ドライバーを作成する
ソリューション内に Controllers という新しいフォルダを作成し、RestaurantsController.cs という新しいコントローラーファイルを追加します。 次のコードをファイルにコピーします。
using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Routing.Controllers;using MongoDB.AspNetCore.OData;using MongoDB.Driver;using ODataTest.Models;
namespace ODataTest.Controllers;
public class RestaurantsController : ODataController{ private readonly IQueryable<Restaurant> _restaurants;
public RestaurantsController(IMongoClient client) { var database = client.GetDatabase("sample_restaurants"); _restaurants = database.GetCollection<Restaurant>("restaurants") .AsQueryable(); }
// Registers Get endpoint and sets max documents to 5 [MongoEnableQuery(PageSize = 5)] public ActionResult<IEnumerable<Restaurant>> Get() { return Ok(_restaurants); }}このコードは、次のアクションを実行します。
MongoDBに接続し、
restaurantsコレクションを取得するコンストラクターを作成します。コレクション内のすべてのレストランを返す
Getエンドポイントを作成します。Getエンドポイントでのクエリを有効にするには、MongoEnableQuery属性を指定します。返されるドキュメント数を
5に制限するには、MongoEnableQueryにPageSize属性を指定します。
OData サービスを構成する
次のコードを Program.csファイルに貼り付けて、OData サービスを構成し、コントローラー エンドポイントをマッピングします。
using Microsoft.AspNetCore.OData;using Microsoft.OData.ModelBuilder;using MongoDB.Bson.Serialization.Conventions;using MongoDB.Driver;using ODataTest.Models;
var builder = WebApplication.CreateBuilder(args);
// Registers a convention pack to convert fields to camel casevar camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };ConventionRegistry.Register( "CamelCase", camelCaseConvention, type => true);
builder.Services.AddSingleton<IMongoClient>( new MongoClient("<Your connection URI>"));
// Registers the Restaurants entity and sets the Id field as the keyvar modelBuilder = new ODataConventionModelBuilder();modelBuilder.EntitySet<Restaurant>("Restaurants");modelBuilder.EntityType<Restaurant>().HasKey(r => r.Id);
// Adds OData and specify query capabilitiesbuilder.Services.AddControllers().AddOData( options => options.Select() .AddRouteComponents("odata", modelBuilder.GetEdmModel()));
var app = builder.Build();app.UseRouting();app.MapControllers();
app.Run();注意
<"Your connection URI"> プレースホルダーをMongoDB接続文字列に置き換えます。
このコードは、次のアクションを実行します。
新しい
MongoClientをインスタンス化し、 依存関係インジェクションコンテナに シングル として登録します。エンティティ データモデル(EDM)を定義し、
RestaurantsをキーIdのエンティティセットとして登録します。OData サービスを追加し、
Select()クエリ操作を有効にします。AddRouteComponents()メソッドを使用してルートを登録します。UseRouting()メソッドとMapControllers()メソッドを呼び出して、受信HTTPリクエストを照合し、適切なエンドポイントにルーティングします。
注意
.NET/ C#ドライバーは、 $apply クエリ操作を使用した OData 集計をサポートしていません。
アプリケーションの実行
IDE を使用するか、プロジェクトのルートディレクトリにあるシェルで次のコマンドを実行中て、アプリケーションを実行します。
dotnet run ODataExample.csprojアプリケーション を実行中と、ターミナルには次のような出力が表示されます。
info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5183info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.info: Microsoft.Hosting.Lifetime[0] Hosting environment: Developmentinfo: Microsoft.Hosting.Lifetime[0] Content root path: <Path to your project>Tip
アプリケーションの実行中後、IDE はアプリケーションがを実行中URLへのブラウザウィンドウを自動的に開き、"page can't be found" エラーを表示します。 これは予想されるもので、アプリケーションには単一の Get エンドポイントしか設定されていないためです。
データのクエリ
データをクエリするには、アプリケーションで指定された Get エンドポイントに移動します。 そのためには、ブラウザを開き、前のステップのターミナル出力で指定されている localhost URLに移動します。 次に、Get エンドポイントのルートを追加します: /odata/Restaurants。 例、アプリケーションが localhost:5183 で実行中いる場合は、http://localhost:5183/odata/Restaurants に移動します。
成功した場合、ブラウザにはコレクション内の 5 レストランがJSON形式で表示されます。 出力は、次のようになります。
{ "@odata.context": "http://localhost:5183/odata/$metadata#Restaurants", "value": [ { "Name": "Glorious Food", "RestaurantId": "40361521", "Cuisine": "American", "Borough": "Manhattan", "Id": "...", "Address": { "Building": "522", "Coordinates": [-73.95171, 40.767461], "Street": "East 74 Street", "ZipCode": "10021" }, "Grades": [ ... ] },
...
]}詳細情報
ASP .NET Core OData の詳細については、Microsoft OData ドキュメント を参照してください。
OData の詳細については、OData のドキュメント を参照してください。