Docs Menu
Docs Home
/ /

MongoDB Entity Framework 및 ASP .NET Core와 통합

이 가이드 에서는 OData 엔드포인트를 제공하고 Entity Framework(EF) Core Provider를 사용하여 MongoDB 에 액세스 ASP .NET Core 애플리케이션 만드는 방법을 학습 수 있습니다. ASP .NET Core는 클라우드 기반 애플리케이션을 만들기 위한 크로스 플랫폼 프레임워크 입니다. OData는 RESTful API를 빌드하고 사용하기 위한 표준화된 프로토콜 이며, 이를 통해 HTTP 요청을 사용하여 데이터와 상호 작용 작용할 수 있습니다.

이 튜토리얼의 애플리케이션 다음과 같은 계층으로 구성되어 있습니다.

  • 데이터베이스 계층: MongoDB 데이터 저장 및 검색을 제공합니다.

  • 애플리케이션 계층: ASP .NET Core는 HTTP 요청, 라우팅 및 종속성 주입을 처리합니다.

  • 데이터 액세스 계층: EF Core Provider는 MongoDB 문서 매핑 및 OData 쿼리 변환을 제공합니다.

이 튜토리얼에서는 MongoDB 용 Entity Framework(EF) Core Provider와 함께 ASP .NET Core OData 프레임워크 사용하여 쿼리 가능한 REST API를 만듭니다. OData는 데이터를 노출하고 데이터와 상호 작용 균일한 방법을 제공하며 필터링, 정렬, 페이징, 필드 선택과 같은 고급 쿼리 기능을 제공합니다.

MongoDB ASP .NET Core 및 OData와 통합하면 EF의 친숙한 패턴과 MongoDB의 유연한 문서 모델 및 OData의 쿼리 기능을 사용할 수 있습니다. 이 조합은 복잡한 쿼리 인터페이스, 유형 안전성 및 표준 기반 API 설계가 필요한 애플리케이션을 지원합니다. MongoDB, ASP .NET Core 및 OData를 사용하여 데이터 분석 대시보드, 보고 시스템 또는 복잡한 데이터 쿼리가 필요한 모든 애플리케이션 과 같은 실제 애플리케이션을 만들 수 있습니다.

이 튜토리얼에서는 MongoDB, ASP .NET Core 및 EF Core 제공자를 사용하는 OData REST API 빌드 방법을 보여줍니다. 이 애플리케이션 샘플 레스토랑 데이터에 액세스하고, OData 호환 엔드포인트를 노출하며, 필터링, 정렬, 페이징, 필드 선택과 같은 고급 쿼리 기능을 지원합니다. 이 튜토리얼에는 MongoDB Atlas 에서 호스팅되는 MongoDB cluster 에 연결하기 위한 지침도 포함되어 있습니다.

ASP .NET Core 없이 EF Core 제공자를 사용하여 MongoDB 에 연결하려는 경우 Entity Framework Provider Quick Start 튜토리얼을 참조하세요.

이 섹션의 단계에 따라 프로젝트 종속성을 설치하고, Atlas 클러스터를 만들고, 애플리케이션 구조를 설정하세요.

1

빠른 시작 애플리케이션 만들려면 개발 환경에 다음 소프트웨어를 설치하세요.

전제 조건
참고 사항

.NET 8.0 이상을 설치합니다.

코드 편집기

원하는 코드 편집기를 사용하세요.

터미널 앱 및 shell

Windows 사용자의 경우 PowerShell 또는 명령 프롬프트를 사용하세요. macOS/ Linux 사용자의 경우 터미널 또는 유사한 앱 사용하세요.

2

MongoDB Atlas 는 MongoDB 배포를 호스팅하는 완전 관리형 클라우드 데이터베이스 서비스입니다. MongoDB deployment 없는 경우,MongoDB 시작하기 튜토리얼을 완료하여 MongoDB cluster 무료로 만들 수 있습니다. MongoDB 시작하기 튜토리얼에서는 sample_restaurants 이 튜토리얼에서 사용되는 데이터베이스 포함하여 샘플 데이터 세트를 클러스터 에 로드하는 방법도 보여줍니다.

MongoDB cluster 에 연결하려면 연결 문자열 사용해야 합니다. 연결 문자열 조회 방법을 학습 MongoDB 시작하기 튜토리얼의 연결 문자열 추가하기 섹션을 참조하세요.

중요

연결 string 을 안전한 위치 에 저장합니다.

3

터미널에서 다음 명령을 실행 RestaurantODataApi이라는 새 ASP .NET Core Web API 프로젝트 만듭니다.

dotnet new webapi -n RestaurantODataApi
cd RestaurantODataApi
4

RestaurantODataApi 디렉토리 에서 다음 명령을 실행 필요한 NuGet 패키지를 추가합니다.

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

이 명령은 다음 패키지를 설치합니다.

  • MongoDB.EntityFrameworkCore: MongoDB EF 코어 제공자

  • 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 라는 파일 만들고 다음 코드를 추가합니다.

레스토랑ODataApi/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 라는 파일 만들고 다음 코드를 추가합니다.

레스토랑ODataApi/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에서 파생됩니다. 이 코드는 MongoDB 와 함께 작동하도록 EF를 구성하고 Restaurant 엔터티를 sample_restaurants.restaurants 컬렉션 에 매핑합니다.

3

RestaurantODataApi 디렉토리 에서 Controllers 하위 디렉토리를 만듭니다. 그런 다음 하위 디렉토리에 RestaurantsController.cs 라는 파일 추가하고 다음 코드를 붙여넣습니다.

레스토랑ODataApi/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 파일 로 이동하여 해당 내용을 다음 코드로 바꿉니다.

레스토랑ODataApi/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 connection
var 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 client
builder.Services.AddSingleton<IMongoClient>(sp => new MongoClient(connectionString));
// Registers the DbContext
builder.Services.AddDbContext<RestaurantDbContext>(options =>
{
var mongoClient = new MongoClient(connectionString);
options.UseMongoDB(mongoClient, databaseName);
});
// Configures the OData EDM model
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Restaurant>("Restaurants");
modelBuilder.EntityType<Restaurant>().HasKey(r => r.Id);
// Registers the unbound functions
var 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 Core
builder.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:5236
info: 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'
    {"@odata.context":"http://localhost:5236/odata/$metadata#Restaurants",
    "value":[
    {"Id":"...","Name":"Riviera Caterer","Cuisine":
    "American","Borough":"Brooklyn","RestaurantId":"40356018"},
    {"Id":"...","Name":"Wilken'S Fine Food","Cuisine":
    "Delicatessen","Borough":"Brooklyn","RestaurantId":"40356483"},
    {"Id":"...","Name":"Kosher Island","Cuisine":
    "Jewish/Kosher","Borough":"Staten Island","RestaurantId":"40356442"},
    {"Id":"...","Name":"Wendy'S","Cuisine":"Hamburgers",
    "Borough":"Brooklyn","RestaurantId":"30112340"},
    {"Id":"...","Name":"Morris Park Bake Shop","Cuisine":
    "Bakery","Borough":"Bronx","RestaurantId":"30075445"}
    ]}
  2. 자치구별로 레스토랑을 필터링합니다.

    다음 명령은 borough 값이 "Queens"인 레스토랑을 검색합니다.

    curl 'http://localhost:5236/odata/GetRestaurantsByBorough(borough=%27Queens%27)?$top=5'
    {"@odata.context":"http://localhost:5236/odata/$metadata#Restaurants",
    "value":[
    {"Id":"...","Name":"Tov Kosher Kitchen","Cuisine":"Jewish/Kosher",
    "Borough":"Queens","RestaurantId":"40356068"},
    {"Id":"...","Name":"Brunos On The Boulevard","Cuisine":"American",
    "Borough":"Queens","RestaurantId":"40356151"},
    {"Id":"...","Name":"Carvel Ice Cream","Cuisine":"Ice Cream, Gelato, Yogurt, Ices",
    "Borough":"Queens","RestaurantId":"40361322"},
    {"Id":"...","Name":"Sal'S Deli","Cuisine":"Delicatessen",
    "Borough":"Queens","RestaurantId":"40361618"},
    {"Id":"...","Name":"Steve Chu'S Deli & Grocery","Cuisine":"Delicatessen",
    "Borough":"Queens","RestaurantId":"40361998"}
    ]}
  3. 요리별로 레스토랑을 필터링합니다.

    다음 명령은 cuisine 값이 "Mexican"인 레스토랑을 검색합니다.

    curl 'http://localhost:5236/odata/GetRestaurantsByCuisine(cuisine=%27Mexican%27)?$top=5'
    {"@odata.context":"http://localhost:5236/odata/$metadata#Restaurants",
    "value":[
    {"Id":"...","Name":"Panchito'S","Cuisine":"Mexican","Borough":"Manhattan"},
    {"Id":"...","Name":"Mexico Lindo Restaurant","Cuisine":"Mexican","Borough":"Manhattan"},
    {"Id":"...","Name":"Casa Pepe","Cuisine":"Mexican","Borough":"Brooklyn"},
    {"Id":"...","Name":"Cuchifrito","Cuisine":"Mexican","Borough":"Manhattan"},
    {"Id":"...","Name":"Mary Ann'S","Cuisine":"Mexican","Borough":"Manhattan"}
    ]}
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)'
    {"@odata.context":"http://localhost:5236/odata/$metadata#Restaurants",
    "value":[
    {"Id":"...","Name":"New Moon Star Restaurant","Cuisine":"Chinese","Borough":"Queens"},
    {"Id":"...","Name":"Moon Tikka Grill","Cuisine":"Indian","Borough":"Queens"},
    {"Id":"...","Name":"Silver Moon Diner","Cuisine":"American","Borough":"Queens"},
    {"Id":"...","Name":"Mooney'S Public House","Cuisine":"Irish","Borough":"Queens"},
    {"Id":"...","Name":"Moon Light Crill Rest","Cuisine":"Indian","Borough":"Queens"},
    {"Id":"...","Name":"Full Moon Cafe","Cuisine":"Café/Coffee/Tea","Borough":"Queens"},
    {"Id":"...","Name":"Pacific Moon","Cuisine":"Chinese","Borough":"Queens"},
    {"Id":"...","Name":"Moon Palace Kitchen","Cuisine":"Chinese","Borough":"Queens"},
    {"Id":"...","Name":"Honey Moon Coffee Shop","Cuisine":"Café/Coffee/Tea","Borough":"Queens"},
    {"Id":"...","Name":"Honey Moon Coffee Shop","Cuisine":"Café/Coffee/Tea","Borough":"Queens"}
    ]}%
  2. 결과를 주문하고 계산합니다.

    다음 명령은 cuisine 필터하다 와 일치하는 문서를 name 값을 기준으로 정렬하고 일치하는 총 문서 수를 계산합니다.

    curl 'http://localhost:5236/odata/GetRestaurantsByCuisine(cuisine=%27Czech%27)?$orderby=Name&$count=true'
    {"@odata.context":"http://localhost:5236/odata/$metadata#Restaurants",
    "@odata.count":6,
    "value":[
    {"Id":"...","Name":"Bohemian Beer Garden","Cuisine":"Czech","Borough":"Queens"},
    {"Id":"...","Name":"Brooklyn Beet Company","Cuisine":"Czech","Borough":"Brooklyn"},
    {"Id":"...","Name":"Hospoda","Cuisine":"Czech","Borough":"Manhattan"},
    {"Id":"...","Name":"Koliba Restaurant","Cuisine":"Czech","Borough":"Queens"},
    {"Id":"...","Name":"Milan'S Restaurant","Cuisine":"Czech","Borough":"Brooklyn"},
    {"Id":"...","Name":"Olde Prague Tavern","Cuisine":"Czech","Borough":"Queens"}
    ]}

EF, ASP .NET 및 OData 빠른 시작 튜토리얼을 완료한 것을 축하합니다! 이 단계를 완료하면 MongoDB deployment 에 연결하고, OData 엔드포인트를 사용하여 레스토랑 데이터를 반환하고, 필터링, 정렬, 페이징, 필드 선택 및 검색과 같은 고급 쿼리 기능을 지원하는 ASP .NET Core OData REST API 갖게 됩니다.

이 튜토리얼에 언급된 개념에 대해 자세히 학습 다음 리소스를 참조하세요.

돌아가기

호환성

이 페이지의 내용