Published on
🍵 2 min read

Integrating MongoDB with .NET Using the EF Core Provider

Authors

Photo by Domenico Loia on Unsplash

Overview

The MongoDB EF Core provider enables .NET developers to use Entity Framework Core (EF Core) with MongoDB.

What is the MongoDB EF Core Provider?

The MongoDB EF Core provider allows the use of EF Core patterns and methods with MongoDB, providing a familiar experience for .NET developers working with NoSQL databases. It supports LINQ queries, migrations, and the unit of work pattern, making MongoDB integration seamless.

How to Set It Up

  1. Add the Package: Install the MongoDB.EntityFrameworkCore package using NuGet:

    dotnet add package MongoDB.EntityFrameworkCore
    
  2. Configure the DbContext:

    public class BlogContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
    
        public BlogContext(DbContextOptions<BlogContext> options) : base(options)
        {
        }
    }
    
    public class Post
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }
    
  3. Register the DbContext in the DI Container: Configure dependency injection for the context in Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddDbContext<BlogContext>(options =>
        options.UseMongoDB("mongodb://localhost:27017", "BlogDatabase"));
    
    var app = builder.Build();
    

Examples

Create Endpoint

app.MapPost("/api/posts", async (Post post, BlogContext context) =>
{
    post.Id = Guid.NewGuid();
    context.Posts.Add(post);
    await context.SaveChangesAsync();
    return Results.Ok(post);
});

List Endpoint

app.MapGet("/api/posts", async (BlogContext context) =>
{
    var posts = await context.Posts.ToListAsync();
    return Results.Ok(posts);
});

Cons

GridFS: The EF Core provider does not natively support GridFS, MongoDB's file storage system used for storing large files like images or videos. Developers needing to work with GridFS must use the official MongoDB C# driver directly, bypassing the EF Core provider.

Conclusion

The MongoDB EF Core provider simplifies MongoDB integration in .NET applications by enabling developers to use familiar EF Core patterns and methods. Using SaveChanges helps implement the unit of work pattern.