client.GetServer()已弃用,我该如何修复它?

时间:2016-07-20 13:45:56

标签: asp.net-web-api2 mongodb-.net-driver

我的代码块:

   public StudentsUnitOfWork()
        {
            var connectionString = ConfigurationManager.AppSettings["MongoDBConectionString"];
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            var databaseName = ConfigurationManager.AppSettings["MongoDBDatabaseName"];
            _database = server.GetDatabase(databaseName);
        }

VS 2015我得到client.GetServer() deprecated , how can I fixed it?

在我改为使用之后:

public StudentsUnitOfWork()
        {
            var connectionString = ConfigurationManager.AppSettings["MongoDBConectionString"];
            var client = new MongoClient(connectionString);
           // var server = client.GetServer();
            var databaseName = ConfigurationManager.AppSettings["MongoDBDatabaseName"];
            _database = client.GetDatabase(databaseName);
        }

它说,不能隐式转换类型..

1 个答案:

答案 0 :(得分:1)

这是我的整个背景,对我来说效果很好:

public class MyContext
{
    public const string COLLECTION_NAME = "CollectionName";

    private static readonly IMongoClient _client;
    private static readonly IMongoDatabase _database;
    static MyContext()
    {
        var connectionString = ConfigurationManager.AppSettings["MongoDBConectionString"];
        _client = new MongoClient(connectionString);
        var databaseName = ConfigurationManager.AppSettings["MongoDBDatabaseName"];
        _database = _client.GetDatabase(databaseName);
    }

    public IMongoClient Client
    {
        get { return _client; }
    }

    public IMongoCollection<TDocument> DocumentType =>
        _database.GetCollection<TDocument>(COLLECTION_NAME);
}