1

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");
}
Community
  • 1
  • 1

1 Answers1

0

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");
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
  • The constructor no longer has as any errors. It does now mean that the methods for the class have errors. For example this method : `public IEnumerable GetUsers() { return _db.GetCollection("Users").FindAll(); }` The error is "IMongoCollection does not contain a definition and no extenstion method FindAll accepting a first arguement of type iMongoCollection could not be found" – James Marshall-Osborne Feb 08 '17 at 17:30
  • Instead of findall you could use .Find(x=>true).ToEnumerable() – Maksim Simkin Feb 08 '17 at 18:22