How to Integrate Azure Cosmos DB for MongoDB with ASP.NET Core: Step-by-Step Tutorial by info.odysseyx@gmail.com October 18, 2024 written by info.odysseyx@gmail.com October 18, 2024 0 comment 6 views 6 As a software developer, you are always looking for ways to build scalable, high-performance applications. Azure Cosmos DB for MongoDB It offers the flexibility of MongoDB with the reliability and global reach of Azure. This blog covers Azure Cosmos DB for MongoDB. ASP.NET Core It walks you through the key steps to setting up a simple API to perform CRUD operations. This powerful combination can help streamline your development process and open up new possibilities for data-driven projects. In the previous blog we Features of Azure Cosmos DB for MongoDB using the Open MongoDB shell in the Azure portal. Be sure to check it out to understand the basics. Topics Covered Create an ASP.NET Core web application Connect to Azure Cosmos DB for MongoDB Perform CRUD operations on data Test your API using the REST client in Visual Studio Code prerequisites To achieve this goal: Create an ASP.NET Core web application ASP.NET Core Web Applications is a high-performance, cross-platform framework for building modern, cloud-enabled web applications and services. To check if you have the .NET SDK installed, open a terminal and run the following command: dotnet –version I will use .NET 8: To create ASP.NET Core web applicationStart by running the following command in the terminal: This creates a new web API project and opens it in Visual Studio Code, a lightweight and versatile code editor. dotnet new webapi --use-controllers -o LibraryWebApi cd LibraryWebApi code . Now that your project is set up, the next step is MongoDB.Driver A package that provides the tools needed to interact with MongoDB databases. that MongoDB.Driver The package is the official MongoDB client library for .NET and provides support for seamlessly connecting, querying, and managing data in MongoDB databases within ASP.NET Core applications. To install a package from NuGet, open an integrated terminal in your project folder and run the following command: dotnet add package MongoDB.Driver This adds the MongoDB driver to your project, allowing you to integrate MongoDB operations into your application.. Packages are added to: LibraryWebApi.csproj Azure Cosmos DB for MongoDB A fully managed NoSQL, relational, and vector database designed for modern app development. Known for its low latency and high-performance features, Azure Cosmos DB for MongoDB supports fast response times. It allows you to interact with it as if it were a standard MongoDB database, making it easy to integrate into existing MongoDB-based applications. In this blog well prove How to create a simple library web API crud (create, read, update, delete) Operations using Azure Cosmos DB for MongoDB. Model settings To get started, let’s define our data model. From the project root in Solution Explorer model folder. first author A class that represents a collection of authors in a database. Create an author model Add the following files inside the Models folder. author.cs Include the following code: using System; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace LibraryWebApi.Models; public class Author { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string? Id { get; set; } [BsonElement("Name")] public required string Name { get; set; } [BsonElement("Bio")] public required string Bio { get; set; } } This Author class maps to MongoDB’s Authors collection. The Id field represents the MongoDB object ID, and other properties (Name and Bio) represent fields for each author. rain. making a book model Next, add a file with a different name to the Models folder. Book.cs. This is represent A collection of books in a database. here code from the book class: using System; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace LibraryWebApi.Models; public class Book { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string? Id { get; set; } [BsonElement("Title")] public required string Title { get; set; } [BsonElement("PublishedYear")] public DateOnly PublishedYear { get; set; } [BsonElement("AuthorId")] [BsonRepresentation(BsonType.ObjectId)] public required string AuthorId { get; set; } } The Book class has a property for Title. Publication yearand Author ID The field uses the MongoDB object ID to link each book to an author in the Authors collection. Here’s how to organize your file structure in Visual Studio Code: next, you are You need to create an Azure Cosmos DB resource. Azure portal. Here are detailed steps on how to provision Azure Cosmos DB for MongoDB.V core), see the aforementioned blog post. We provide step-by-step guides to help you set up your resource. Visit the blog here. We have created a cluster with a name. cosmos-mongodb. To connect your application to the newly created resource, go to Settings and retrieve the connection string. using this string establish Connection between application and database. memo: Keep your connection string confidential. Never expose it to a public repository or share it publicly. your app settings.json Add the connection string you copied from your Azure Cosmos DB resource to the file, along with the name of the database you want to create. This example uses: Library DBAutomatically created when the application starts. Below is app settings.json: { "ConnectionStrings": { "MongoDB": "mongodb+srv://:@cosmos-mongodb.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000" }, "MongoDB": { "DatabaseName": "LibraryDB" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" } Now that your connection string is set up, the next step is DbContext Handles interaction with the database. Inside the Models folder, create a new folder like this: DbContext. Add the following files to the DbContext folder: MongoDbContext.cs. that MongoDB context The class manages database interactions and provides access to book and author collections. Copy code below and paste MongoDbContext.cs. using System; using MongoDB.Driver; namespace LibraryWebApi.Models.DbContext; public class MongoDbContext { private readonly IMongoDatabase _database; // used to interact with the database public MongoDbContext(IConfiguration configuration) { var client = new MongoClient(configuration.GetConnectionString("MongoDB")); //connect to the database _database = client.GetDatabase(configuration["MongoDB:DatabaseName"]); } public IMongoCollection Books => _database.GetCollection("Books"); public IMongoCollection Authors => _database.GetCollection("Authors"); } This should be the project structure and file format. Next you need to set up: singleton pattern It’s in Program.cs, which serves as the entry point to the application. The singleton pattern registers the MongoDbContext class with the dependency injection container, ensuring that only one instance of this class is created and shared across the entire application. This approach is important for maintaining consistent connections to the database and managing data integrity. To register MongoDbContext as a singleton service, add the following line of code: builder.Services.AddSingleton(); You should also configure JSON serialization options to avoid the default camel case during serialization (converting objects to JSON). you can achieve this correction The controller settings are as follows: builder.Services.AddControllers() .AddJsonOptions( options =>options.JsonSerializerOptions.PropertyNamingPolicy = null); This configuration ensures that property names in the JSON output match their original case in the C# model. Perform CRUD operations on data Next, we create the controllers needed to perform CRUD operations on the Books and Authors collections. To do this, create two files. Written byController.cs and BooksController.csClick and add the following code to each file: Written byController.cs file using System; using LibraryWebApi.Models; using LibraryWebApi.Models.DbContext; using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; namespace LibraryWebApi.Controllers; [ApiController] [Route("api/[controller]")] public class AuthorsController : ControllerBase { private readonly MongoDbContext _context; public AuthorsController(MongoDbContext context) //passing the context to the controller { _context = context; } [HttpGet] public async Task>> GetAuthors() { var authors = await _context.Authors.Find(author => true).ToListAsync(); return Ok(authors); } [HttpGet("{id}")] public async Task> GetAuthor(string id) { var author = await _context.Authors.Find(author => author.Id == id).FirstOrDefaultAsync(); if (author == null) { return NotFound(); } return Ok(author); } [HttpPost] public async Task CreateAuthor(Author author) { await _context.Authors.InsertOneAsync(author); return CreatedAtAction(nameof(GetAuthor), new { id = author.Id }, author); } [HttpPut("{id}")] public async Task UpdateAuthor(string id, Author updatedAuthor) { var authorToUpdate = await _context.Authors.Find(author => author.Id == id).FirstOrDefaultAsync(); if (authorToUpdate is null) { return NotFound(); } updatedAuthor.Id = authorToUpdate.Id; await _context.Authors.ReplaceOneAsync(author => author.Id == id, updatedAuthor); return NoContent(); } [HttpDelete("{id}")] public async Task DeleteAuthor(string id) { var result = await _context.Authors.DeleteOneAsync(author => author.Id == id); if (result.IsAcknowledged && result.DeletedCount > 0) { return NoContent(); } return NotFound(); } } rain. BooksController.cs file using System; using LibraryWebApi.Models; using LibraryWebApi.Models.DbContext; using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; namespace LibraryWebApi.Controllers; [Route("api/[controller]")] [ApiController] public class BooksController : ControllerBase { public readonly MongoDbContext _context; public BooksController(MongoDbContext context) { _context = context; } [HttpGet] public async Task>> GetBooks() { var books = await _context.Books.Find(book => true).ToListAsync(); return Ok(books); } [HttpGet("{id}")] public async Task> GetBook(string id) { var book = await _context.Books.Find(book => book.Id == id).FirstOrDefaultAsync(); if (book == null) { return NotFound(); } return Ok(book); } [HttpPost] public async Task CreateBook(Book book) { await _context.Books.InsertOneAsync(book); return CreatedAtAction(nameof(GetBook), new { id = book.Id }, book); } [HttpPut("{id}")] public async Task UpdateBook(string id, Book updatedBook) { var bookToUpdate = await _context.Books.Find(book => book.Id == id).FirstOrDefaultAsync(); if (bookToUpdate is null) { return NotFound(); } updatedBook.Id = bookToUpdate.Id; await _context.Books.ReplaceOneAsync(book => book.Id == id, updatedBook); return NoContent(); } [HttpDelete("{id}")] public async Task DeleteBook(string id) { var result = await _context.Books.DeleteOneAsync(book => book.Id == id); if (result.IsAcknowledged && result.DeletedCount > 0) { return NoContent(); } return NotFound(); } } Now try building your project to see if you can build it successfully without any issues. Run the following command in terminal: dotnet build Once the build completes successfully, run the application by running the following command in the terminal: dotnet run Your API runs on local hostYou can start testing your application by running it in your browser. We recommend that you enable hot reload, which automatically restarts the API whenever you change a file. You can also run your API securely over HTTPS by trusting the HTTPS certificate. These options are optional and can be adjusted according to your preferences. Create a new file and give it a name. louchSettings.json. Insert the following code into the file: memo: The port number on which the API will run may not be the same as my port number. { "profiles": { "https": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://localhost:71992", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "hotReloadEnabled": true } } } This setting allows you to run the application using the following command: dotnet watch run --launch-profile https Test your API using the REST client in Visual Studio Code Now it’s time to test your API! I am REST client extensionYou can install it in Visual Studio Code. This extension is efficient because it allows you to test endpoints directly within the editor without having to switch to an external tool. Created by: 2. Get all authors: 3. Get one author 4. Author update: 5. Delete author The same applies to your book collection. let’s do it Return to the Azure portal and verify that your database, collection, and data were saved successfully. Sign in to the Azure portal, navigate to the resource you created, and click Next. Quick Start (Preview) To access mongo shell. opening mongo shell When prompted, enter the password you set for your cluster. To see the available databases, run the following command: show dbs To use an available database: Use LibraryDB To see all collections Database: show collections To view data in your collection, follow these steps: db.Authors.find().pretty() db.Books.find().pretty() The results obtained after running the above command are: Thank you for taking the time to read my blog! In this post, you’ve successfully demonstrated how to connect Azure Cosmos DB for MongoDB to an ASP.NET web application through a small project. I encourage you to build your skills. you are Use the information you gain here to add more features to your application. We hope you find this learning experience enjoyable and inspiring. Happy coding! Learn more Create a web API using ASP.NET Core and MongoDB Query documents in Azure Cosmos DB for MongoDB using .NET Manage documents in Azure Cosmos DB for MongoDB using .NET Get started with Azure Cosmos DB for MongoDB using JavaScript Get started with Azure Cosmos DB for MongoDB and Python Comparing MongoDB Atlas to Azure Cosmos DB for MongoDB Azure Cosmos DB Developer Specializations Source link Share 0 FacebookTwitterPinterestEmail info.odysseyx@gmail.com previous post Explore Exciting Inside Sales Intern Opportunities at Recipeat Bangalore for Career Growth and Experience next post Exploring the Power of Codespaces for Student Developers You may also like The Sonos Arc Ultra raises the bar for home theater audio December 5, 2024 Aptera Motors will showcase its solar EV at CES 2025 December 3, 2024 How Chromebook tools strengthen school cybersecurity December 2, 2024 Nvidia unveils the ‘Swiss Army Knife’ of AI audio tools: Fugato November 26, 2024 Nvidia Blackwell and the future of data center cooling November 25, 2024 Enterprise productivity is the easiest AI sell November 20, 2024 Leave a Comment Cancel Reply Save my name, email, and website in this browser for the next time I comment.