MongoDB MongoClient.GetServer()已弃用。什么是新API?

时间:2015-10-26 12:58:50

标签: c# mongodb

这是我的数据库连接字符串:

private static string ConnectionString = "mongodb://user:password@server:port/";
private static string AuthSource = "?authSource=location";

public static MongoCollection<ItemEntity> GetMyItemCollectionDB = new MongoClient(ConnectionString + DBName + AuthSource)
.GetServer().GetDatabase(DBName).GetCollection<ItemEntity>(CollectionName);

我听说您可以放弃getserver方法:

public static MongoCollection<ItemEntity> GetMyItemCollectionDB = new MongoClient(ConnectionString + DBName + AuthSource)
  .GetDatabase(DBName)
  .GetCollection<ItemEntity>(CollectionName) as MongoCollection<ItemEntity>;

但是为此,我得到一个&#34; null对象&#34;错误。问题是什么?

编辑:如果使用新API并不重要,那就告诉我。

2 个答案:

答案 0 :(得分:2)

要获取MongoServer实例,我解组汇编MongoDB.Driver.dll, GetServer函数是

[Obsolete("Use the new API instead.")]
public static MongoServer GetServer(this MongoClient client)
{
    return 
MongoServer.Create(MongoServerSettings.FromClientSettings(client.Settings));
} 

所以你可以试试下面的代码

MongoClient client = new MongoClient(ConnectionString + DBName + AuthSource);
MongoServer server =  new MongoServer(MongoServerSettings.FromClientSettings(client.Settings));
var yourCollection = server.GetDatabase(DBName).GetCollection<ItemEntity>(CollectionName);

版本2.0.0 +中有4种方法

MongoDB.Driver.MongoServer.Create(MongoServerSettings)
MongoDB.Driver.MongoServer.WithReadConcern(ReadConcern)
MongoDB.Driver.MongoServer.WithReadPreference(ReadPreference)
MongoDB.Driver.MongoServer.WithWriteConcern(WriteConcern)

答案 1 :(得分:0)

我相信你知道你的第二个代码最后会返回IMongoCollection<ItemEntity>

但是,MongoCollection不会从IMongoCollection继承,这就是您最终获得NULL值的原因。