- Published on
Integrating MongoDB with .NET Using the EF Core Provider
- Authors
- Name
- Emin Vergil
- @eminvergil
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
Add the Package: Install the
MongoDB.EntityFrameworkCore
package using NuGet:dotnet add package MongoDB.EntityFrameworkCore
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; } }
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 allowing developers to use familiar EF Core patterns and methods. Additionally, leveraging SaveChanges
supports implementing the unit of work pattern, ensuring consistency and reliability in database operations.