Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

mongo-efcore-provider

> 数据库
Open source

MongoDB Entity Framework Core Provider

398 stars0 likes0 views
WebsiteGitHub

About

MongoDB Entity Framework Core Provider

MongoDB Entity Framework Core Provider

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.

Getting Started

Basic Setup

First, create a DbContext with the desired entities and configuration:

internal class PlanetDbContext : DbContext
{
    public DbSet Planets { get; init; }

    public static PlanetDbContext Create(IMongoDatabase database) =>
        new(new DbContextOptionsBuilder()
            .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName)
            .Options);

    public PlanetDbContext(DbContextOptions options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity().ToCollection("planets");
    }
}

Connection Options

Option 1: Direct Database Connection

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");

Option 2: Using Dependency Injection

var mongoConnectionString = builder.Configuration.GetConnectionString("MongoDbUri")!;
builder.Services.AddDbContext(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(mongoClient);
builder.Services.AddDbContext((provider, options) =>
{
    var client = provider.GetRequiredService();
    options.UseMongoDB(client, DatabaseName);
});

Later on, simply inject PlanetDbContext where it's needed and continue as you would normally.

Supported Features

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, Take etc.
  • Vector search with the VectorSearch extension 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 or HasElementName("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, Guid and ObjectId etc.
  • Properties with typical CLR types (int, string, Guid, decimal, DateOnly etc.) & 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, BsonRepresentation and BsonRequired support
  • 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 & EnsureDeleted to ensure collections and the database created at app start-up
  • Optimistic concurrency support through IsConcurrencyToken/ConcurrencyCheckAttribute & IsRowVersion/TimestampAttribute
  • AutoTransactional SaveChanges & SaveChangesAsync - all changes committed or rolled-back together
  • CamelCaseElementNameConvention for helping map Pascal-cased C# properties to camel-cased BSON elements
  • Type discriminators including OfType and Where(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 ExecuteUpdate and ExecuteDelete (EF 9+) on a single collection; supports constant and self-referencing setters; bypasses the change tracker (concurrency tokens are not checked)
    • Where-scoped sources execute as a single atomic deleteMany / updateMany server command
    • Sources that also use OrderBy/ThenBy/Skip/Take/Distinct are supported via a transactional two-phase execution (phase 1 collects the target _ids; phase 2 acts on them via { _id: { $in: [...] } }); requires a transaction-capable deployment (replica set or sharded cluster); under AutoTransactionBehavior.Never the caller must open an explicit transaction
    • 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

Limitations

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.

Planned for future releases

  • Select projections with client-side operations
  • GroupBy operations
  • Includes/joins
  • Geospatial

Not supported, out-of-scope features

  • Keyless entity types
  • Migrations
  • Database-first & model-first
  • Document (table) splitting
  • Temporal tables
  • Timeseries
  • GridFS

Breaking changes

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.

Documentation

  • MongoDB
  • EF Core Provider Guide
  • EF Core Provider API Docs

Questions/Bug Reports

  • Forums
  • Jira

If you've identified a security vulnerability in a driver or any other MongoDB project, please report it according to the instructions here.

Contributing

Please see our guidelines for contributing to the driver.

Thank you to everyone who has contributed to this project.

Issues· 8 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#csharpentity-frameworkentity-framework-coremongodb

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库