C# MongoDB.Driver - 如何构造构造函数

C# MongoDB.Driver - How to form a constructor

我目前正在按照在线教程为 MongoDB 创建 RESTful API。该指南包括用于 CRUD 功能的 DataAccess class。它使用旧的 MongoDB API,现在 deprecated.There 是客户端、服务器和数据库的三个变量,然后有一个 class:

的构造函数
MongoClient _client;
MongoServer _server;
MongoDatabase _db;

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

新的 API 不需要服务器变量,因此您只需直接在客户端上调用 (),但我在使用构造函数时遇到了问题。这就是我所拥有的,但是在构造函数中的 _db 代码行抛出 "Cannot implicitly convert type" 错误:

MongoClient _client;
MongoDatabase _db;

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

MongoClient.GetDatabase returns IMongoDatabase 接口.

将您的代码更改为:

MongoClient _client;
IMongoDatabase _db;

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