Search code examples
c#.netmongodbrestmongodb-.net-driver

C# MongoDB.Driver - How to form a constructor


I am currently following an online tutorial to create a RESTful API for MongoDB. The guide includes a DataAccess class for CRUD functionality. It is using the old MongoDB API which is now deprecated.There are three variables for Client, Server and Database and then has a constructor for the class:

MongoClient _client;
MongoServer _server;
MongoDatabase _db;

public DataAccess()
{
    _client = new MongoClient("mongodb://localhost:27017");
    _server = _client.GetServer();
    _db = _server.GetDatabase("EmployeeDB");      
}

The new API does not need the server variable so you just call directly on the client (C# MongoDB.Driver GetServer is Gone, What Now?) but I'm having trouble with the constructor. This is what I have but is throwing a "Cannot implicitly convert type" error for the _db line of code in the constructor:

MongoClient _client;
MongoDatabase _db;

public DataAccess()
{
    _client = new MongoClient("mongodb://localhost:27017");
    _db = _client.GetDatabase("Users");
}

Solution

  • MongoClient.GetDatabase returns IMongoDatabase interface.

    Change your code to:

    MongoClient _client;
    IMongoDatabase _db;
    
    public DataAccess()
    {
        _client = new MongoClient("mongodb://localhost:27017");
        _db = _client.GetDatabase("Users");
    }