C#MongoDB.Driver-如何形成构造函数
我目前正在学习为MongoDB创建RESTful API的在线教程。该指南包括一个用于CRUD功能的DataAccess类。它使用的是旧的MongoDB API,现已弃用。客户端、服务器和数据库有三个变量,然后类有一个构造函数:C#MongoDB.Driver-如何形成构造函数,c#,.net,mongodb,rest,mongodb-.net-driver,C#,.net,Mongodb,Rest,Mongodb .net Driver,我目前正在学习为MongoDB创建RESTful API的在线教程。该指南包括一个用于CRUD功能的DataAccess类。它使用的是旧的MongoDB API,现已弃用。客户端、服务器和数据库有三个变量,然后类有一个构造函数: MongoClient _client; MongoServer _server; MongoDatabase _db; public DataAccess() { _client = new MongoClient("mongodb://localhost:
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
返回IMongoDatabase
接口
将代码更改为:
MongoClient _client;
IMongoDatabase _db;
public DataAccess()
{
_client = new MongoClient("mongodb://localhost:27017");
_db = _client.GetDatabase("Users");
}
MongoClient.GetDatabase
返回IMongoDatabase
接口
将代码更改为:
MongoClient _client;
IMongoDatabase _db;
public DataAccess()
{
_client = new MongoClient("mongodb://localhost:27017");
_db = _client.GetDatabase("Users");
}
构造函数不再具有任何错误。它现在确实意味着类的方法有错误。例如,此方法:
public IEnumerable GetUsers(){return_db.GetCollection(“用户”).FindAll()}
错误是“IMongoCollection不包含定义,并且找不到接受IMongoCollection类型的第一个参数的扩展方法FindAll”您可以使用.Find(x=>true).ToEnumerable()代替findall,构造函数不再具有任何错误。它现在确实意味着类的方法有错误。例如,此方法:public IEnumerable GetUsers(){return_db.GetCollection(“用户”).FindAll()}
错误是“IMongoCollection不包含定义,并且找不到接受IMongoCollection类型的第一个参数的扩展方法FindAll”您可以使用.Find(x=>true).ToEnumerable()代替findall