In this guide, you will learn how to configure an application to use the MongoDB Entity Framework Core Provider. To learn how to set up a new project and install the EF Core Provider, see the Quick Start.
Create a POCO
Create a Plain old CLR/Class object, or POCO, to use as a model for your entity. A POCO is a simple class object that doesn't inherit features from any framework-specific base classes or interfaces.
The following code example shows how to create a POCO that represents a customer:
public class Customer { public ObjectId Id { get; set; } public string Name { get; set; } = null!; public string Order { get; set; } = null!; }
Tip
To learn more about POCOs, see the POCO guide in the .NET/C# Driver documentation.
Create a DB Context Class
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.
The DBContext class exposes DBSet properties that specify the entities you
can interact with while using that context.
The following example creates an instance of a DBContext derived class and
specifies the Customer object as a DBSet property:
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"); } }
The previous code example overrides the OnModelCreating() method. Overriding
the OnModelCreating() method allows you to specify configuration details for your
model and its properties. This example uses the ToCollection() method to
specify that the Customer entities in your application map to the
customers collection in MongoDB.
Use MongoDB
Once you've created a DBContext class, construct a
DbContextOptionsBuilder object and call its UseMongoDB() method. This
method takes two parameters: a MongoClient instance and
the name of the database that stores the collections you are working with.
The UseMongoDB() method returns a DbContextOptions object. Pass the
Options property of this object to the constructor for your DBContext
class.
The following example shows how to construct a DBContext object in
this way:
var mongoClient = new MongoClient("<connection string>"); var dbContextOptions = new DbContextOptionsBuilder<MyDbContext>().UseMongoDB(mongoClient, "<database name>"); var db = new MyDbContext(dbContextOptions.Options);
Tip
Creating a MongoClient
You can call methods from the MongoDB .NET/C# Driver when using
the EF Core Provider. The previous example uses the
MongoClient() method from the .NET/C# Driver to create a MongoDB
client that connects to a MongoDB instance.
To learn more about using the MongoDB .NET/C# Driver to connect to MongoDB, see the Connection guide in the .NET/C# Driver documentation.
MongoClient and DbContext Lifetimes
The lifetime and configuration of your MongoClient and DbContext objects
directly affect memory usage and connection pool efficiency.
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.
Example
The following code example shows how to register services by using dependency injection, configure the EF Core Provider, and insert a document into the database:
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>"); }); 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(); }