The MongoDB EF Core Provider enables MongoDB interaction with Entity Framework Core 8 or 9 on .NET 8.0 or later, and Entity Framework Core 10 on .NET 10.0 or later.
It supports MongoDB database server 5.0 or later, preferably in a transaction-enabled configuration.
First, create a DbContext with the desired entities and configuration:
internal class PlanetDbContext : DbContext
{
public DbSet<Planet> Planets { get; init; }
public static PlanetDbContext Create(IMongoDatabase database) =>
new(new DbContextOptionsBuilder<PlanetDbContext>()
.UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName)
.Options);
public PlanetDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Planet>().ToCollection("planets");
}
}var mongoConnectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
var mongoClient = new MongoClient(mongoConnectionString);
var db = PlanetDbContext.Create(mongoClient.GetDatabase("planets"));
db.Database.EnsureCreated();
var planet = db.Planets.FirstOrDefault(x => x.Name == "Earth");var mongoConnectionString = builder.Configuration.GetConnectionString("MongoDbUri")!;
builder.Services.AddDbContext<PlanetDbContext>(options =>
{
options.UseMongoDB(mongoConnectionString, DatabaseName);
});If you need some more configuration, you can create the MongoClient and inject it into the DbContext:
var mongoConnectionString = builder.Configuration.GetConnectionString("MongoDbUri")!;
var mongoUrl = new MongoUrl(mongoConnectionString);
var mongoClient = new MongoClient(mongoUrl);
builder.Services.AddSingleton<IMongoClient>(mongoClient);
builder.Services.AddDbContext<PlanetDbContext>((provider, options) =>
{
var client = provider.GetRequiredService<IMongoClient>();
options.UseMongoDB(client, DatabaseName);
});Later on, simply inject PlanetDbContext where it's needed and continue as you would normally.
Entity Framework Core and MongoDB have a wide variety of features. This provider supports a subset of the functionality available in both, specifically:
-
Querying with
Where,Find,First,Single,OrderBy,ThenBy,Skip,Takeetc. -
Vector search with the
VectorSearchextension method on DbSet and fluent vector index configuration -
Top-level aggregate
Any,Count,LongCount,Sum,Min,Max,Average,All -
Mapping properties to BSON elements using
[Column]or[BsonElement]attributes orHasElementName("name")method -
Mapping entities to collections via
[Table("name")],ToCollection("name")or by convention from the DbSet property name -
Single or composite keys of standard types including string,
GuidandObjectIdetc. -
Properties with typical CLR types (
int,string,Guid,decimal,DateOnlyetc.) & MongoDB types (ObjectId,Decimal128) -
Properties that are arrays, lists, dictionaries (string keys) of simple CLR types including binary
byte[] -
Owned entities (aka value types, sub-documents, embedded documents) both directly and in collection properties
-
BsonIgnore,BsonId,BsonDateTimeOptions,BsonElement,BsonRepresentationandBsonRequiredsupport -
Storage type configuration through EF ValueConverters or BSON representation attributes and fluent APIs
-
Query and update logging of MQL (sensitive logging must be enabled)
-
EnsureCreated&EnsureDeletedto ensure collections and the database created at app start-up. From EF9,EnsureCreated[Async]also runs the delegates set withUseSeeding/UseAsyncSeedingafter the collections, indexes andHasDatarows exist. As for relational providers they run on every call, so they must be idempotent; theirboolargument istruewhen the database did not exist before the call (the valueEnsureCreatedreturns, so it isfalsewhen only some collections were missing);EnsureCreatedneedsUseSeedingandEnsureCreatedAsyncneedsUseAsyncSeeding. Unlike relational providers, the delegate is not wrapped in a transaction: its ownSaveChangesis transactional as usual, and works withEnableRetryOnFailure -
Optimistic concurrency support through
IsConcurrencyToken/ConcurrencyCheckAttribute&IsRowVersion/TimestampAttribute. A row version must be a non-nullableint,uint,longorulong, or abyte[](as used with SQL Serverrowversion); the provider increments it on every write (abyte[]is an 8-byte big-endian counter) and stores it in the_versionelement (unless an element name is configured for the property). Any other row version type is rejected when the model is built. To use aulongin code and bytes in the database, useIsRowVersion().HasConversion<byte[]>() -
AutoTransactional
SaveChanges&SaveChangesAsync- all changes committed or rolled-back together -
Sharing a transaction between contexts:
context.Database.UseTransaction(...)makes a context write and query inside a transaction it did not start, so several contexts (even on differentMongoClientinstances connected to the same cluster, including a sharded cluster) can take part in one transaction. Pass another context's transaction, or anIClientSessionHandlethat already has a transaction started:using var owner = new BlogContext(blogOptions); // DbContextOptions<BlogContext> using var other = new AuthorContext(authorOptions); // DbContextOptions<AuthorContext> using var transaction = owner.Database.BeginTransaction(); owner.Blogs.Add(new Blog { Name = "Mongo" }); owner.SaveChanges(); other.Database.UseTransaction(transaction); other.Authors.Add(new Author { Name = "Ada" }); other.SaveChanges(); owner.Database.CommitTransaction(); // only the owner ends the transaction
-
The transaction is not owned by the context that joins it: disposing it (or the context) only detaches, and
Commit/Rollbackon it, orDatabase.CommitTransaction()/RollbackTransaction()on the joining context, throwInvalidOperationException. Only the owner (or the code that supplied the session) commits or aborts. This differs from relational providers, whereCommit/Rollbackon a transaction joined withUseTransactionact on it and onlyDisposeis skipped -
A joined context is detached by disposing the transaction
UseTransactionreturned (or by disposing the context);UseTransaction(null)is not supported -
Disposing a context rolls back a transaction that context started and has not committed or rolled back (as relational providers do), so contexts that joined it can no longer write; commit before disposing the owner
-
With the driver's
session.WithTransaction(...), a retry (after aTransientTransactionError) aborts the transaction and starts a new one on the same session, and a context enlisted before the retry then throwsInvalidOperationException("is no longer active"); that exception carries noTransientTransactionErrorlabel, so the retry stops. Create the context and callUseTransaction(session)inside the callback, and dispose it with the callback:session.WithTransaction((s, ct) => { using var db = new BlogContext(blogOptions); db.Database.UseTransaction(s); // enlist inside the callback, so every retry gets a fresh context db.Blogs.Add(new Blog { Name = "Mongo" }); db.SaveChanges(); return 0; });
-
Once the owner commits or aborts,
SaveChanges, queries and bulkExecuteUpdate/ExecuteDeleteon a joined context throwInvalidOperationException("is no longer active") rather than silently running outside a transaction -
MongoDB has no savepoints: a failed write aborts the whole transaction. The next operation (or, on a sharded cluster, possibly only the commit) fails with the server's
TransientTransactionError, and nothing from the transaction becomes visible -
Schema operations never take part in the transaction:
EnsureCreated/EnsureDeletedand the collection and index creation they perform run outside it, are committed immediately and are not rolled back. Seed data written byEnsureCreateddoes join the transaction -
Server limits apply:
$search/$vectorSearchqueries are rejected inside a multi-document transaction. The provider passes the server error through unchanged. (The server also restrictsdropandcreateIndexesinside a transaction, which only matters for your own driver code run on the shared session) -
A client session is not thread-safe: contexts sharing a transaction must be used one at a time, never concurrently
-
Ambient
System.Transactions(TransactionScope,Database.EnlistTransaction) and savepoints remain unsupported -
Joining logs
MongoEventId.TransactionEnlistedand detaching (disposing the joined context or its transaction) logsMongoEventId.TransactionDetached, both at Information and both naming the owner; a joined context logs no commit or rollback events. When a context's own transaction is disposed after something else already ended the session's transaction,MongoEventId.TransactionRollbackSkippedrecords that there was nothing to roll back
-
-
Retrying transient transaction failures:
UseMongoDB(..., o => o.EnableRetryOnFailure())(defaults: 6 retries, at most 30 seconds between them) makes EF Core's execution strategy (context.Database.CreateExecutionStrategy(), whichSaveChangesalso uses) re-run a unit of work when MongoDB aborts its transaction and labels the errorTransientTransactionError, for example a write conflict between two concurrent transactions:var strategy = db.Database.CreateExecutionStrategy(); strategy.Execute(() => { db.ChangeTracker.Clear(); // a failed attempt leaves its entities tracked using var transaction = db.Database.BeginTransaction(); db.Orders.First().Status = "Shipped"; db.SaveChanges(); transaction.Commit(); });
- Off by default, so nothing changes for existing applications. Retrying is always from the start of the delegate: the failed transaction was aborted, and MongoDB has no savepoints
- Only the
TransientTransactionErrorlabel is retried, not specific error codes. Duplicate-key and other deterministic write errors,DbUpdateConcurrencyExceptionand cancellation are never retried, and neither is work that did not run inside a transaction (AutoTransactionBehavior.Never, or aSaveChangeswith a single root entity underWhenNeeded): a failure there can leave earlier writes applied, and running them again could apply them twice. The driver's own retryable reads and writes still retry single operations as before - As with relational providers, a retrying strategy rejects a transaction started outside the delegate (
Database.BeginTransaction()orDatabase.UseTransaction(...)followed bySaveChanges): "use the execution strategy returned byCreateExecutionStrategy()to execute all the operations in the transaction as a retriable unit". WithoutEnableRetryOnFailuresuch transactions work as before.SaveChangeswithout an outer transaction needs nothing extra: it retries its own implicit transaction - Each attempt starts a new session and transaction. A context that joined the failed transaction with
UseTransaction(see above) throws "is no longer active" if used again, instead of writing outside a transaction, so create such contexts and join them inside the delegate - Independently of
EnableRetryOnFailure,Commit/CommitAsyncon a transaction the context started retries the commit on the same session when MongoDB reportsUnknownTransactionCommitResult(the commit may or may not have been applied; committing again applies it at most once), for up to two minutes, unless the server'smaxTimeMSexpired. Each retry logsMongoEventId.TransactionCommitRetryingat Warning. A transaction the context only joined cannot be committed through EF, so the owner's code decides - Retries of the whole unit of work are logged by EF Core's
CoreEventId.ExecutionStrategyRetrying. Behavior on a sharded cluster has not been tested
-
CamelCaseElementNameConventionfor helping map Pascal-cased C# properties to camel-cased BSON elements -
Type discriminators including
OfType<T>andWhere(e => e is T) -
Support for EF shadow properties and EF.Proxy for navigation traversal
-
MongoDB full text search (Previously known as Atlas Search)
-
MongoDB vector search (Previously known as Atlas Vector Search)
-
Client Side Field Level Encryption and Queryable Encryption compatibility
-
Bulk
ExecuteUpdateandExecuteDelete(EF 9+) on a single collection; supports constant and self-referencing setters; bypasses the change tracker (concurrency tokens are neither checked nor protected: a bulk update may set one explicitly)Where-scoped sources, including ones that also useOrderBy/ThenBy/Distinct(they do not change which documents match), execute as a singledeleteMany/updateManyserver command. This is not an atomic multi-document operation: MongoDB guarantees atomicity per document only, so concurrent readers may observe partial results and a failure part-way leaves the documents already written changed. Open an explicit transaction around the call if you need all-or-nothing semantics- Sources that use
Skip/Take, orOfType<TDerived>()on a hierarchy, are supported via a transactional two-phase execution (phase 1 collects the target_ids, reading only the_id; phase 2 acts on them via{ _id: { $in: [...] } }, in batches of up to 50,000 ids inside the one transaction); requires a transaction-capable deployment (replica set or sharded cluster); underAutoTransactionBehavior.Neverthe caller must open an explicit transaction.Castis not supported - Setters cannot target the primary key or the type discriminator (rejected before anything is written). Setting the same property twice keeps the last value
- Global query filters are applied, and
IgnoreQueryFilters()removes them, as for a read - Queryable Encryption:
ExecuteDeleteworks (an equality filter on an encrypted field matches the intended documents), butExecuteUpdateis rejected by Queryable Encryption because every bulk update is anupdateMany("Multi-document updates are not allowed with Queryable Encryption"); useSaveChangesinstead. Client-Side Field Level Encryption has not been verified with bulk operations - If a transaction is already open on the context, the operation enlists in it rather than starting its own — MongoDB does not support nested transactions, so a two-phase bulk op cannot open an inner transaction the way some relational providers do
- Not supported: joins,
GroupBy,SelectMany, set operations, cross-document navigation predicates, or multiple-collection updates
A number of Entity Framework Core features are not currently supported but planned for future release. If you require use of these facilities in the mean-time consider using the existing MongoDB C# Driver's LINQ provider which may support them.
- Select projections with client-side operations
- GroupBy operations
- Includes/joins
- Geospatial
- Keyless entity types
- Migrations
- Database-first & model-first
- Document (table) splitting
- Temporal tables
- Timeseries
- GridFS
This project's version-numbers are aligned with Entity Framework Core and as-such we can not use the semver convention of constraining breaking changes solely to major version numbers. Please keep an eye on our Breaking Changes document before upgrading to a new version of this provider.
If you've identified a security vulnerability in a driver or any other MongoDB project, please report it according to the instructions here.
Please see our guidelines for contributing to the driver.
Thank you to everyone who has contributed to this project.