AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

MongoDBと Entity フレームワーク および ASP .NET Core を統合

このガイドでは、OData エンドポイントを提供し、Entity Framework(EF)コア プロバイダーを使用してMongoDBにアクセスする ASP.NET Core アプリケーションを作成する方法を学習できます。ASP .NET Core は、クラウドベースのアプリケーションを作成するためのクロスプラットフォームフレームワークです。OData は、RESTul API をビルドして消費するための標準化されたプロトコルであり、 HTTPリクエストを使用してデータをやり取りできます。

このチュートリアルのアプリケーションは、次のレイヤーで構成されています。

  • データベースレイヤー: MongoDB は、データのストレージと検索を提供します。

  • アプリケーションレイヤー: ASP .NET Core は、 HTTPリクエスト、ルーティング、依存関係インジェクションを取り扱います。

  • データ アクセスレイヤー: FS コア プロバイダーは、 MongoDBドキュメントマッピングと OData クエリの変換を提供します。

このチュートリアルでは、ASP .NET Core ODataフレームワークとMongoDB用の Entity Framework(FS)コア プロバイダーを使用して、クエリ可能な REST API を作成します。OData は、データを公開してやり取りする統一された方法を提供し、フィルタリング、ソート、ページング、フィールド選択などの高度なクエリ機能を提供します。

MongoDB を ASP.NET Core および OData と統合することで、EF の使い慣れたパターンを MongoDB の柔軟な document model と OData のクエリ機能と組み合わせて使用できます。この組み合わせは、複雑なクエリ インターフェース、型の安全性、標準ベースのAPI設計を必要とするアプリケーションをサポートします。MongoDB、 ASP .NET Core、OData を使用して、データ分析ダッシュボード、レポート作成システム、複雑なデータクエリを必要とするアプリケーションなどの本番環境のアプリケーションを作成できます。

このチュートリアルでは、 MongoDB、ASP .NET Core、およびLF Core プロバイダーを使用する OData REST APIをビルドする方法について説明します。このアプリケーションは、サンプルレストラン データにアクセスし、OData 準拠のエンドポイントを公開し、フィルタリング、ソート、ページング、フィールド選択などの高度なクエリ機能をサポートします。チュートリアルには、 MongoDB AtlasでホストされているMongoDBクラスターに接続するための手順も含まれています。

Tip

ASP.NET Core を使用せずに EF Core プロバイダーを使用して MongoDB に接続する場合は、Entity Framework プロバイダーのクイック スタート チュートリアルを参照してください。

このセクションの手順に従って、プロジェクトの依存関係のインストール、Atlas クラスターの作成、およびアプリケーション構造の設定を行います。

1

クイック スタートアプリケーションを作成するには、開発環境に次のソフトウェアをインストールします。

前提条件
ノート

.NET 8.0 以降をインストールします。

コードエディター

お好みのコード エディターを使用してください。

ターミナルアプリとシェル

Windowsユーザーの場合は、 PowerShell または コマンドプロンプトを使用します。macOS/ Linuxユーザーの場合は、 ターミナル または 類似アプリを使用します。

2

MongoDB Atlas は、 MongoDB配置をホストするフルマネージドクラウドデータベースサービスです。MongoDBの配置がない場合は、MongoDBを使い始める チュートリアルを完了することで、 MongoDBクラスターを無料で作成できます。MongoDBを使い始める チュートリアルでは、このチュートリアルで使用される sample_restaurantsデータベースなど、サンプルデータセット をクラスターにロードする方法も説明します。

MongoDBクラスターに接続するには、接続文字列を使用する必要があります。接続文字列を取得する方法については、 MongoDBを使い始めるチュートリアルの「 接続文字列列の追加 」セクションを参照してください。

重要

接続stringを安全な場所に保存します。

3

ターミナルから次のコマンドを実行して、RestaurantODataApi という名前の新しい ASP .NET Core Web APIプロジェクトを作成します。

dotnet new webapi -n RestaurantODataApicd RestaurantODataApi
4

RestaurantODataApiディレクトリで、次のコマンドを実行して必要な NuGet パッケージを追加します。

dotnet add package MongoDB.EntityFrameworkCoredotnet add package Microsoft.AspNetCore.OData

これらのコマンドは、次のパッケージをインストールします。

  • MongoDB.EntityFrameworkCore: MongoDB FS コア プロバイダー

  • Microsoft.AspNetCore.OData: ASP .NET Core の OData サポート

5

RestaurantODataApiプロジェクト内の appsettings.jsonファイルに移動し、次のコードを貼り付けます。

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "MongoDB": { "ConnectionString": "<connection string>", "DatabaseName": "sample_restaurants" }}

<connection string> プレースホルダーを、 MongoDBを使い始める チュートリアルから保存した接続文字列に置き換えます。

プロジェクト構造と依存関係を設定したら、このセクションの手順に従って、データモデル、DbContext、OData エンドポイントを作成します。

1

RestaurantODataApiディレクトリに、Models サブディレクトリを作成します。次に、Modelsディレクトリに Restaurant.cs という名前のファイルを作成し、次のコードを追加します。

RestaurantODataApi/Models/Restaurant.cs

using Microsoft.EntityFrameworkCore;using MongoDB.Bson;using MongoDB.Bson.Serialization.Attributes;using System.ComponentModel.DataAnnotations; namespace RestaurantODataApi.Models{ public class Restaurant { [Key] [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } = string.Empty; [BsonElement("name")] public string? Name { get; set; } [BsonElement("cuisine")] public string? Cuisine { get; set; } [BsonElement("borough")] public string? Borough { get; set; } }}

このモデルクラスは、 MongoDB sample_restaurants.restaurantsコレクションのレストラン データの構造を定義し、 Entity Framework とMongoDB直列化属性を含みます。

2

RestaurantODataApiディレクトリに、RestaurantDbContext.cs という名前のファイルを作成し、次のコードを追加します。

restaurantODataApi/RestaurantDbContext.cs

using Microsoft.EntityFrameworkCore;using MongoDB.Driver;using MongoDB.EntityFrameworkCore.Extensions;using RestaurantODataApi.Models; namespace RestaurantODataApi{ public class RestaurantDbContext : DbContext { public DbSet<Restaurant> Restaurants { get; set; } public RestaurantDbContext(DbContextOptions<RestaurantDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Configures the Restaurant entity to map to the "restaurants" collection modelBuilder.Entity<Restaurant>().ToCollection("restaurants"); } }}

このクラスは、モデルと基礎となるデータベースの間の関係を構成する DBContext から派生します。このコードは、F をMongoDBで動作するように構成し、Restaurant エンティティを sample_restaurants.restaurantsコレクションにマッピングします。

3

RestaurantODataApiディレクトリに、Controllers サブディレクトリを作成します。次に、RestaurantsController.cs という名前のファイルを サブディレクトリに追加し、次のコードを貼り付けます。

RestaurantODataApi/Controllers/RestaurantsController.cs

using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.OData.Query;using Microsoft.AspNetCore.OData.Routing.Controllers;using Microsoft.AspNetCore.OData.Routing.Attributes;using RestaurantODataApi.Models; namespace RestaurantODataApi.Controllers{ public class RestaurantsController : ODataController { private readonly RestaurantDbContext _context; public RestaurantsController(RestaurantDbContext context) { _context = context; } [EnableQuery(PageSize = 50, AllowedQueryOptions = AllowedQueryOptions.All)] public IQueryable<Restaurant> Get() { return _context.Restaurants; } [HttpGet("odata/GetRestaurantsByBorough(borough={borough})")] [EnableQuery(PageSize = 20)] public IQueryable<Restaurant> GetRestaurantsByBorough(string borough) { return _context.Restaurants.Where(r => r.Borough == borough); } [HttpGet("odata/GetRestaurantsByCuisine(cuisine={cuisine})")] [EnableQuery(PageSize = 20)] public IQueryable<Restaurant> GetRestaurantsByCuisine(string cuisine) { return _context.Restaurants.Where(r => r.Cuisine == cuisine); } }}

このコントローラーは、次の OData REST エンドポイントとなる接続されたデバイスを定義します。

  • GET /odata/Restaurants: restaurantsコレクション内のすべてのドキュメントを取得します。EnableQuery 属性とその構成オプションを使用すると、 HTTPリクエストで $filter や $orderby などの OData クエリ パラメータを使用できます。

  • GET /odata/GetRestaurantsByBorough(borough='{borough}'): 指定された borough 値を持つドキュメントを取得します。

  • GET /odata/GetRestaurantsByCuisine(cuisine='{cuisine}'): 指定された cuisine 値を持つドキュメントを取得します。

4

Program.csファイルに移動し、その内容を次のコードで置き換えます。

RestaurantODataApi/Program.cs

using Microsoft.AspNetCore.OData;using Microsoft.EntityFrameworkCore;using Microsoft.OData.ModelBuilder;using MongoDB.Driver;using RestaurantODataApi;using RestaurantODataApi.Models; var builder = WebApplication.CreateBuilder(args); // Configures the MongoDB connectionvar connectionString = builder.Configuration["MongoDB:ConnectionString"];var databaseName = builder.Configuration["MongoDB:DatabaseName"] ?? "sample_restaurants"; if (string.IsNullOrEmpty(connectionString)){ throw new InvalidOperationException("MongoDB connection string is required. Please set MongoDB:ConnectionString in appsettings.json");} // Registers a MongoDB clientbuilder.Services.AddSingleton<IMongoClient>(sp => new MongoClient(connectionString)); // Registers the DbContextbuilder.Services.AddDbContext<RestaurantDbContext>(options =>{ var mongoClient = new MongoClient(connectionString); options.UseMongoDB(mongoClient, databaseName);}); // Configures the OData EDM modelvar modelBuilder = new ODataConventionModelBuilder();modelBuilder.EntitySet<Restaurant>("Restaurants");modelBuilder.EntityType<Restaurant>().HasKey(r => r.Id); // Registers the unbound functionsvar getRestaurantsByBoroughFunction = modelBuilder.Function("GetRestaurantsByBorough");getRestaurantsByBoroughFunction.Parameter<string>("borough");getRestaurantsByBoroughFunction.ReturnsCollectionFromEntitySet<Restaurant>("Restaurants"); var getRestaurantsByCuisineFunction = modelBuilder.Function("GetRestaurantsByCuisine");getRestaurantsByCuisineFunction.Parameter<string>("cuisine");getRestaurantsByCuisineFunction.ReturnsCollectionFromEntitySet<Restaurant>("Restaurants"); // Configures OData with ASP.NET Corebuilder.Services.AddControllers() .AddOData(opt => opt .AddRouteComponents("odata", modelBuilder.GetEdmModel()) .Select() .Filter() .OrderBy() .Expand() .Count() .SetMaxTop(100)); var app = builder.Build(); app.UseRouting();app.MapControllers(); app.Run();

このコードは、 MongoDB接続、Entity Framework DbContext、OData サービスを設定します。OData 構成コードにより、次のクエリ パラメータが有効になり、 HTTPエンドポイントとなる接続されたデバイスで使用できます。

  • $select: 結果内の指定されたフィールドを返します

  • $filter: フィルター条件に基づいてデータを返します

  • $orderby: 指定されたフィールドで結果をソートします

  • $expand: 結果に関連データを含める

  • $count: 結果のカウントを含めます

  • $top: 結果の最大数を設定します。 100

最後に、このセクションの手順に従ってOData REST APIを実行し、 HTTPリクエストを使用してエンドポイントをテストします。

1

RestaurantODataApiディレクトリから、次のコマンドを実行してアプリケーションをコンパイルして起動します。

dotnet run

成功した場合、コマンド出力は次の例のようになります。

info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5236info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.
2

別のターミナルで、次の curl コマンドを実行して、OData エンドポイントをテストします。各エンドポイントとなる接続されたデバイスは、sample_restaurants.restaurantsコレクションのレストラン情報を含む OData形式のJSONデータを返します。成功した場合、curl コマンドはサンプル出力のようなデータを返します。コマンドは結果を 5 ドキュメントに制限します。

  1. すべてのレストランを検索します。

    curl 'http://localhost:5236/odata/Restaurants?$top=5'
  2. レストランを地区別にフィルターで絞り込みます。

    次のコマンドは、borough 値が "Queens" であるレストランを検索します。

    curl 'http://localhost:5236/odata/GetRestaurantsByBorough(borough=%27Queens%27)?$top=5'
  3. レストランを料理別にフィルターします。

    次のコマンドは、cuisine 値が "Mexican" であるレストランを検索します。

    curl 'http://localhost:5236/odata/GetRestaurantsByCuisine(cuisine=%27Mexican%27)?$top=5'
3

エンドポイントを使用して、OData クエリ パラメーターと演算子を含めることで、複雑なクエリを実行できます。次の curl コマンドは、これらの機能をテストします。

  1. 複数のフィールドでフィルターします。

    次のコマンドでは、OData クエリ演算子を使用して、borough 値が "Queens" で、かつ name 値が "Moon" を含むドキュメントを検索します。

    curl 'http://localhost:5236/odata/Restaurants?$filter=Borough%20eq%20%27Queens%27%20and%20contains(Name,%20%27Moon%27)'
  2. 結果を順序付けてカウントします。

    次のコマンドは、cuisine フィルターに一致するドキュメントを name 値でソートし、一致するドキュメントの合計数をカウントします。

    curl 'http://localhost:5236/odata/GetRestaurantsByCuisine(cuisine=%27Czech%27)?$orderby=Name&$count=true'

FS、 ASP .NET、 OData クイック スタート チュートリアルを完了しました。これらの手順を完了すると、 MongoDB**配置**に接続し、 OData エンドポイントを使用してレストランのデータを返し、 フィルター、ソート、ページング、フィールド選択、検索などの高度な**クエリ機能**をサポートする ASP .NET Core OData REST API が作成されます。

このチュートリアルで述べられた概念の詳細については、次のリソースを参照してください。