AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

EF 코어 제공자 구성

이 가이드에서는 MongoDB Entity 프레임워크 Core 제공자를 사용하도록 애플리케이션을 구성하는 방법을 학습합니다. 새 프로젝트를 설정하고 EF 코어 제공자를 설치하는 방법을 학습하려면 EF 코어 제공자 시작하기를 참조하세요.

엔터티의 모델로 사용할 일반 이전 CLR/클래스 객체 또는 POCO를 만듭니다. POCO는 프레임워크별 기본 클래스나 인터페이스의 기능을 상속하지 않는 간단한 클래스 객체 입니다.

다음 코드 예제에서는 고객을 나타내는 POCO를 만드는 방법을 보여 줍니다.

public class Customer
{
public ObjectId Id { get; set; }
public string Name { get; set; } = null!;
public string Order { get; set; } = null!;
}

POCO에 대해 자세히 알아보려면 .NET/C# 드라이버 설명서에서 POCO 가이드 를 참조하세요.

To begin using Entity Framework Core, create a context class that derives from DBContext. The DbContext derived class instance represents a database session and is used to query and save instances of your entities.

DBContext 클래스는 해당 컨텍스트를 사용하는 동안 상호 작용할 수 있는 엔터티를 지정하는 DBSet 속성을 노출합니다.

다음 예제에서는 DBContext 파생 클래스의 인스턴스를 만들고 Customer 객체를 DBSet 속성으로 지정합니다.

public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; init; } = null!;
public MyDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().ToCollection("customers");
}
}

이전 코드 예시에서는 OnModelCreating() 메서드를 재정의합니다. OnModelCreating() 메서드를 재정의하면 모델 및 해당 속성에 대한 구성 세부 정보를 지정할 수 있습니다. 이 예제에서는 ToCollection() Customer 메서드를 사용하여 customers 애플리케이션의 엔터티가 MongoDB의 collection에 매핑되도록 지정합니다.

DBContext 클래스를 만든 후 DbContextOptionsBuilder 객체를 생성하고 해당 UseMongoDB() 메서드를 호출합니다. 이 메서드는 인스턴스 MongoClient 와 작업 중인 collection을 저장하는 데이터베이스의 이름이라는 두 가지 매개변수를 사용합니다.

UseMongoDB() 메서드는 DbContextOptions 객체를 반환합니다. 이 객체의 Options 속성을 DBContext 클래스의 생성자에 전달합니다.

다음 예제에서는 이러한 방식으로 DBContext 객체를 구성하는 방법을 보여 줍니다.

var mongoClient = new MongoClient("<connection string>");
var dbContextOptions =
new DbContextOptionsBuilder<MyDbContext>().UseMongoDB(mongoClient, "<database name>");
var db = new MyDbContext(dbContextOptions.Options);

MongoClient 만들기

EF Core Provider를 사용할 때 MongoDB .NET/ C# 드라이버 에서 메서드를 호출할 수 있습니다. 이전 예시 에서는 .NET/ C# 드라이버 의 MongoClient() 메서드를 사용하여 MongoDB 인스턴스 에 연결하는 MongoDB 클라이언트 를 만듭니다.

MongoDB .NET/C# 드라이버를 사용하여 MongoDB에 연결하는 방법에 대해 자세히 알아보려면 .NET/C# 드라이버 설명서의 연결 가이드 를 참조하세요.

MongoClientDbContext 객체의 수명과 구성은 메모리 사용량과 연결 풀 효율성에 직접적으로 영향을 미칩니다.

Register MongoClient as a singleton and share a single instance across all DbContext registrations. Because each MongoClient object manages its own internal connection pool, creating a separate instance for each DbContext scope wastes connections and increases latency. To learn more, see Manage MongoClient Disposables in the .NET/C# Driver documentation.

Register DbContext as a scoped service so that each request uses a new change tracker. A singleton DbContext accumulates tracked entity state across all requests, which causes stale data, memory growth, and increasingly slow change-detection as the tracker grows larger. To learn more, see DbContext in Dependency Injection for ASP.NET Core in the Microsoft Entity Framework Core documentation.

다음 코드 예시에서는 의존 주입을 사용하여 서비스를 등록하고 EF Core Provider를 구성하고 데이터베이스에 문서를 삽입하는 방법을 보여 줍니다.

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IMongoClient>(
new MongoClient("<connection string>"));
serviceCollection.AddDbContext<MyDbContext>((serviceProvider, options) =>
{
var mongoClient = serviceProvider.GetRequiredService<IMongoClient>();
options.UseMongoDB(mongoClient, "<database name>");
});
using var app = serviceCollection.BuildServiceProvider();
using (var scope = app.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();
// Add a new customer and save it to the database
db.Customers.Add(new Customer() { Name = "John Doe", Order = "1 Green Tea" });
db.SaveChanges();
}