MongoDB in WPF application with example

MongoDB in WPF application with example

In this article, we will see how to get started using MongoDB database using MongoDB C# Driver in the WPF .NET Core application.

We shall create a MongoDB context object which will resemble like EF Core generated DBContext scaffolding (Entity Framework is an ORM framework for relational DB)

We shall be using the MongoDB database as the NoSQL database instance. We shall see and leverage the usage of Mongo DBContext object using Dependency injection.

Here we shall create a Context class which will help us to create abstraction around Mongo object.

Getting Started

Create .NET Core WPF application

MongoDB in WPF application with example

Please add MongoDB driver NuGet package using the Nuget Package manager or PMC command,

PM> Install-Package MongoDB.Driver -Version 2.10.3

OR

MongoDB in WPF application with example

MongoDB Configuration

Below is MongoDB connection configuration defined in appsettings.json.

By default, there will not be any apsettings.json file in the WPF application.

Please add new appsettings.json file to your WPF application and define MongoDB connection string and Database name as below,

{
  "MongoSettings": {
    "ConnectionString": "mongodb://[dbconnectionstring]",
    "DatabaseName": "Book"
  }
}

You can also make use of other configuration files like reading configuration from .ini or .xml or .json file storing the configuration details and retrieve it as required.

Let’s create generic HosBuilder and register the dependencies that need to injected which is explained in detail below.

Register MongoDB Context in DI Container

We will set generic HostBuilder for WPF application.

Please install the NuGet package from Nuget Package manager or PMC,

PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.2

Below is how we have defined the DI container. This gives you an early idea of Interfaces and Classes we shall be creating at the end of this article.

 

public App()
        {
            var builder = Host.CreateDefaultBuilder()
                .ConfigureServices((hostContext, services) =>
                {

                    services.AddScoped<IMongoBookDBContext, MongoBookDBContext>();
                    services.AddSingleton<MainBookWindow>();
                });

            var host = builder.Build();

            using (var serviceScope = host.Services.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
                try
                {
                    var masterWindow = services.GetRequiredService<MainBookWindow>();
                    masterWindow.Show();

                    Console.WriteLine("Success");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error Occured" + ex.Message);
                }
            }
        }

Define MongoDBContext Interface

We shall name Mongo DBContext Interfaces as ‘IMongoBookDBContext‘,

 public interface IMongoBookDBContext
    {
        IMongoCollection<Book> GetCollection<Book>(string name);
    }

Create Mongo DBContext class

Mongo DBContext class will be defined as below,

 public class MongoBookDBContext : IMongoBookDBContext
    {
        private IMongoDatabase _db { get; set; }
        private IMongoClient _mongoClient { get; set; }
        public IClientSessionHandle Session { get; set; }
        public MongoBookDBContext(IOptions<Mongosettings> configuration)
        {
            _mongoClient = new MongoClient(configuration.Value.Connection);

            _db = _mongoClient.GetDatabase(configuration.Value.DatabaseName);
        }
      
        public IMongoCollection<T> GetCollection<T>(string name)
        {
            if(string.IsNullOrEmpty(name))
            {
                return null;
            }
            return _db.GetCollection<T>(name);
        }
    }

above IOptions configuration will load the required configuration within Mongosettings class directly using Type safe configuration technique

Using configuration DBContext class will help to establish an actual connection, providing the database collection as required.

Model Entity as Book

Based on the schema this is how the model class has been defined as below,

public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
 
        public string Name { get; set; }
 
        public decimal Price { get; set; }
 
        public string Category { get; set; }
 
        public string Author { get; set; }
    }

Define MainWindow class

So finally we are all set with Models and types required for us to connect and perform our CRUD operation.

Below we are consuming IMongoBookDBContext using Constructor injection directly in the MainBookWindow. But one can additional layer if needed and then consume the given context if required.

public partial class MainBookWindow : Window
    {
        private readonly IMongoBookDBContext _context;
        protected IMongoCollection<Book> _dbCollection;
        public MainBookWindow(IMongoBookDBContext context)
        {
            InitializeComponent();
            _context = context;
            _dbCollection = _context.GetCollection<Book>(typeof(Book).Name);
        }
    }

Performing CRUD operations

We are using the FindSync method which is an extension method.

Below I am using ObjectId as a unique identifier to read the details about the Book.

  public Book GetBookDetails()
        {
            Console.WriteLine("GetBookDetails operation Started");

            var objectId = new ObjectId("5dc1039a1521eaa36835e541");
            FilterDefinition<Book> filter = Builders<Book>.Filter.Eq("_id", objectId);
            var result = _dbCollection.FindAsync(filter).Result.FirstOrDefaultAsync();
            return result.Result;
        }

Let’s execute the Read operation and verify results using the ButtonClick event as below,

 private void Button_Click(object sender, RoutedEventArgs e)
        {
           Book book = GetBookDetails();
           MessageBox.Show($"Book details are BookName {book.Name} Author {book.Author} ");

        }

We shall see below result ,

MongoDB in WPF application with example

That’s all this was very much basics on using the MongoDB database using MongoDB Driver C# code in the WPF application.

You can very much extend the above application for other CRUD operation like Create, Update or Delete.

Do you need further improvement to this codebase ??

Please do use Repository pattern around MongoDB as discussed in below implementation,

Summary

In this post, we learned how to use MongoDB in a .NET Core WPF application. We learned to create a Context definition for the existing No-SQL database and then leveraged the tiny IoC container to register the DBContext and other objects and performed basic CRUD operation.

Thank you for reading. Please let me know your questions, thoughts or feedback below in the comments section. I appreciate your feedback and encouragement.

Leave a Reply

Your email address will not be published. Required fields are marked *