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."
Step 1. Create a MongoDB Atlas Account
- Visit MongoDB Atlas Website
- 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.
- Verify Your Email
- Check your email inbox for a verification email from MongoDB.
- Click on the verification link to complete the sign-up process.
Step 2. Create a New Cluster
- Login to MongoDB Atlas
- Use your credentials to log in to the MongoDB Atlas dashboard.
- 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."
- Wait for the Cluster to Deploy
- The cluster deployment may take a few minutes. You can monitor the progress on the Atlas dashboard.
Step 3. Connect to the Database
- 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.
- Update Connection String
- Replace <username> and <password> with your Atlas username and password.
- Replace <database> with the name of your data
Step 4. Create a Database and Collection
- Access the Cluster
- Once the cluster is deployed, click on its name to open the cluster details.
- 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."
- 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."
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.
Configuring MongoDB with Entity Framework Core
Step 1. Model Definition
- Define your Model And give it the collection attribute along with the name [Collection("UserDetail")].
- ObjectId-Define the object ID in your model This acts like your document key.
Step 2. MongoDB context Class
The class MongoDB context inherits from DbContext, suggesting it's a database context used to interact with a database.
- 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.
- 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.
- 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.
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’
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.
This data was inserted into the MongoDB Atlas database through the API.
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.