Building CRUD Operations in .NET Core 8 with MongoDB

Introduction

.NET Core 8's Minimal API offers a streamlined way to build lightweight RESTful services. This article explores how to create CRUD (Create, Read, Update, Delete) operations using Minimal API with MongoDB, a popular NoSQL database. We'll demonstrate how to set up a Minimal API, configure MongoDB, and manage data using Entity Framework Core-like patterns. This approach is ideal for those who want to build efficient, scalable applications with document-based storage

Prerequisites

Creating a New Project in Visual Studio

Creating a New Project in Visual Studio 2022 Start the Visual Studio software and select "Create a new project."

New project

Step 1. Create a MongoDB Atlas Account

  1. Visit MongoDB Atlas Website
  2. Sign Up
    • Click on the "Start Free" or "Sign Up" button.
    • Fill in the required information, including your email, password, and other details.
    • Optionally, you can sign up using Google or GitHub authentication.
  3. Verify Your Email
    • Check your email inbox for a verification email from MongoDB.
    • Click on the verification link to complete the sign-up process.
      MongoDB

Step 2. Create a New Cluster

  1. Login to MongoDB Atlas
    • Use your credentials to log in to the MongoDB Atlas dashboard.
  2. Create a New Cluster
    • Click on "Build a Cluster" or "New Cluster."
    • Choose a cloud provider (e.g., AWS, Google Cloud, Azure) and a region.
    • Select the cluster tier (the free tier is typically available for learning and development).
    • Choose a cluster name and click "Create Cluster."
  3. Wait for the Cluster to Deploy
    • The cluster deployment may take a few minutes. You can monitor the progress on the Atlas dashboard.
      Dashboard
      Copy

Step 3. Connect to the Database

  1. Get Connection String
    • In the Atlas dashboard, click "Connect" on your cluster.
    • Choose "Connect Your Application."
    • Select your desired driver and version (e.g., "Node.js," "C# (.NET)").
    • Copy the connection string provided by MongoDB Atlas.
  2. Update Connection String
    • Replace <username> and <password> with your Atlas username and password.
    • Replace <database> with the name of your data
      Connection String
      Apply
      Create

Step 4. Create a Database and Collection

  1. Access the Cluster
    • Once the cluster is deployed, click on its name to open the cluster details.
  2. Create a Database
    • Click on "Collections."
    • Click "Add My Own Data" or "Create Database."
    • Enter a database name (e.g., "sample database") and a collection name (e.g., "sampleCollection").
    • Click "Create."
  3. Add Data to the Collection
    • Click on the new database name (e.g., "sample database").
    • Click on the collection name (e.g., "sampleCollection").
    • Use the "Insert Document" button to add a document to the collection.
    • Enter your JSON data and click "Insert."
      JSON data

Using Visual Studio

  • Open your project in Visual Studio.
  • Right-click on your project in the Solution Explorer.
  • Select "Manage NuGet Packages."
  • Search for "MongoDB.EntityFrameworkCore."
  • Click "Install" to add the package to your project.
    FrameworkCore

Configuring MongoDB with Entity Framework Core

 Entity Framework

.NET

Step 1. Model Definition

  1. Define your Model And give it the collection attribute along with the name [Collection("UserDetail")].
  2. ObjectId-Define the object ID in your model This acts like your document key.
    Model Definition

Step 2. MongoDB context Class

The class MongoDB context inherits from DbContext, suggesting it's a database context used to interact with a database.

  1. Constructor with DbContextOptions
    • The constructor MongoDB context (DbContextOptions dbContextOptions) initializes the base class (DbContext) with the given options. These options typically include database connection information and configuration.
  2. DbSet Property
    • public DbSet<User> users { get; set; }: This property represents a collection of User entities. A DbSet in Entity Framework Core is used to manage a collection of entities and perform CRUD (Create, Read, Update, Delete) operations.
  3. OnModelCreating Method
    • The OnModelCreating(ModelBuilder modelBuilder) method is used to configure entity mappings when the model is being created. This method is usually overridden in a derived DbContext class to customize entity relationships, constraints, etc.
    • The line modelBuilder.Entity<User>().ToCollection("UserDetail") suggests an attempt to map the User entity to a collection named "UserDetail". This syntax resembles MongoDB mapping rather than typical Entity Framework Core mapping.
      Method

Step 3. Service Activation

Specify the database provider and Connection string.

builder.Services.AddScoped<IUserRepository, UserRepository>();

builder.Services.AddDbContext<MongoDBContext>(options =>
{
    var connectionstring = "mongodb connection string";
    var database = "EFCOREDB";
    options.UseMongoDB(connectionstring, database);
});

Step 4. Methods in IUserRepository

List<User> GetAllUserList():

This method returns a list of User objects. It's intended to retrieve all users from a data source, like a database. The exact implementation will depend on the class that implements this interface.

bool AddUser(User user):

This method takes a User object as a parameter and returns a boolean indicating success or failure. It is used to add a new user to a data source. The specific logic for adding a user will be defined in the class that implements this interface.

 public interface IUserRepository
{
    List<User> GetAllUserList();
    bool AddUser(User user);
}
public class UserRepository : IUserRepository
{
    private readonly MongoDBContext _context;

    public UserRepository(MongoDBContext _context)
    {
        this._context = _context;
    }

    public List<User> GetAllUserList()
    {
        var response = _context.users.ToList();
        return response;
    }

    public bool AddUser(User user)
    {
        try
        {
            _context.users.Add(user);
            _context.SaveChanges(); 
            return true;
        }
        catch(Exception ex)
        {
            return false;
        }
    }
}

Dependency Injection: The constructor accepts a MongoDB context instance, indicating that the repository depends on this context to interact with the database.

public UserRepository(MongoDBContext _context)
{
    this._context = _context;
}
app.MapGet("/User/GetAllUser",  (IUserRepository userRepository) =>

{

    var response =  userRepository.GetAllUserList();

    return Results.Ok(response);

});

GET EndPoint: ’/User/GetAllUser’

  • Purpose: This endpoint retrieves a list of all users from the IUserRepository.
  • Method: Uses MapGet to define an HTTP GET endpoint.
  • Response: Returns an HTTP 200 response (Results. OK) with the list of users.
    app.MapPost("/User/New", (IUserRepository userRepository,[FromBody]User user) =>
    {
        var response = userRepository.AddUser(user);
        return Results.Ok(response);
    });
    

POST EndPoint:’/User/New’

  • Purpose: This endpoint adds a new user to the database.
  • Method: Uses MapPost to define an HTTP POST endpoint.
  • Input: Takes a User object from the HTTP request body ([FromBody] User user).
  • Response: Returns an HTTP 200 response (Results. OK) indicating whether the addition was successful or not.
     EndPoint
    Cancel

This data was inserted into the MongoDB Atlas database through the API.

API

URL

Conclusion

Building CRUD operations with .NET Core 8's Minimal API and MongoDB allows for lightweight, scalable, and flexible web services. By using Entity Framework Core-like patterns, you can easily interact with MongoDB collections, enabling efficient data management. This guide has shown you the basics of setting up a Minimal API, connecting to MongoDB, and implementing CRUD operations. Whether you're creating a new project or enhancing an existing one, this approach provides a solid foundation for building RESTful APIs with MongoDB.