Creating your first C# application with MongoDB
The main purpose of this article is to share code and to present some basics principles on how to implement CRUD (Create Read Update Delete) operations in a MongoDB database with C#.
Context
Because of a big event coming soon in my life, I set myself a challenge to create an elegant console app to manage our guest list and track RSVPs: This is how the project Guestlist Manager app started.
Why MongoDB?
Some may wonder why I chose MongoDB over other databases. Here are the factors I considered when choosing my database:
· Dynamic schema: MongoDB gives the flexibility to change data schema without modifying any of the existing data. It’s perfect for this ongoing project.
· Manageability: The database is user-friendly and doesn’t require a database administrator.
· Speed: It’s high performing for simple queries.
· Flexibility: Adding new columns or fields doesn’t affect existing rows or application performance.
· Scalability: MongoDB is horizontally scalable, which helps reduce the workload and scale at ease.
· It’s cheap 😉: You can set up a MongoDB server in your own Virtual Machine or use a cloud database service like MongoDB Atlas starting for free with affordable pricing model.
· A good opportunity for me to learn more about Mongo C# driver, MongoDB Atlas and Stitch: MongoDB is more than a database. It’s a whole ecosystem that comes with many cloud services like database-as-a-service and serverless platform.
Getting our workspace ready
The complete project is available on Github here. Feel free to fork it and clone it for your own use!. To follow along, you will need a MongoDB database you can connect to. You can use a MongoDB database running locally, or easily create a free database using MongoDB Atlas.
· Install Visual Studio and .NET Framework
· Install MongoDB locally or Create a free database using MongoDB Atlas
Creating and running our console application
- Launch Visual Studio
2. Click Create a new project
3. In the Create a new project dialog, click Console App (.NET Core)
4. Name the project “guestlist-manager-cli-csharp”
5. Click Create to create the project
Visual Studio creates a new C# Console Application project and opens the file Programs.cs. Replace the content of Program.cs by copying and pasting the code below into the file.
A C# console application must contain a Main method, in which control starts and ends. The Main method is where you create objects and execute other methods.
Press F5 to build and run the project
Connecting to the MongoDB Database from C#
Adding MongoDB C#/.NET Driver dependencies to our project
What will allow us to work with the data in any MongoDB database from C# is a package called MongoDB C#/.NET Driver which creates a native interface between our application and a MongoDB server.
To install the driver, we’ll go through Nuget and download the package.
1. Open the Package Manager Console in Visual Studio with “Tools -> Nuget Package Manager -> Package Manager Console”
2. Type: “Install-Package MongoDB.Driver”
3. Hit enter
Adding an entity model
— Create GuestModel.cs
1. Click Project -> Add Class
2. Type “GuestModel.cs” in the name field
3. Click Add to add the new class to the project
Copy and paste the following code into the GuestModel.cs file and save.
In that class, the Id property:
· is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
· is annotated with [BsonId] to designate this property as the document’s primary key.
The FullName property is annotated with the [BsonElement] attribute’s value of Name represents the property Name in the MongoDB collection
Adding a MongoDB helper class
— Create MongoHelper.cs
This class is a collection of methods for dealing with MongoDB connection and CRUD operations.
1. Click Project -> Add Class
2. Type “MongoHelper.cs” in the name field
3. Click Add to add the new class to the project
Copy and paste the following code into the MongoHelper.cs file and save.
Styling the console table
— Create ConsoleTable.cs
This class is responsible for drawing a pretty data table in our console app
1. Click Project -> Add Class
2. Type “ConsoleTable.cs” in the name field
3. Click Add to add the new class to the project
Copy and paste the following code into the ConsoleTable.cs file and save.
Adding our application main menu and dialogs
— Create DialogHelper.cs
This class is responsible for displaying the main menu and the dialogs within our app.
1. Click Project -> Add Class
2. Type “DialogHelper.cs” in the name field
3. Click Add to add the new class to the project
Copy and paste the following code into the DialogHelper.cs file and save.
Wiring up everything in Main method
Now everything is good to go, we can wire up everything in Main method.
Open the file Program.cs and replace the content with the following code.
Setting the connection string of our database
In Main method, replace the value of the connection string with your MongoDB server.
To get your connection string from MongoDB Atlas you can follow the instructions from the official documentation: Connect via Driver.
That’s all, our application is ready to run!
Press F5 to build and run the project
Even if you don’t have any existing database named “GuestDatabase” and or a collection named “GuestCollection”, MongoDB will create it for you while inserting your first document.
Wrapping up
Now, we have a fully functional Guestlist Manager console app. We can create, read, update and delete our guest records stored in a MongoDB database. Here is the recap of what we’ve covered:
· Create a C# console application using Visual Studio.
· Connect our application to MongoDB.
· Learn how to execute CRUD operations by using MongoDB C#/.NET Driver.
Next steps
And there we have it! Our Guestlist Manager currently lets us manage the list directly. BUT that’s only half the battle — wouldn’t it be cool if we could also send invitations directly from the database? In my next post, I’ll take this a step further and show you how to do this with MongoDB Stitch and SendGrid.
UPDATE: Check out my next post: Sending Emails with MongoDB Stitch and SendGrid.
Feedback
Thanks for reading! I hope this helped you with your first C# and MongoDB project. I kept this project intentionally simple, and there are many ways it can be built upon and improved. Please feel free to leave a comment here or create an issue in the Github repo — this will help me continue to create content that is most helpful to you and the community. Til next time!