2015-10-26 14 views
1

這是我的連接字符串到我的數據庫:MongoDB MongoClient.GetServer()已棄用。什麼是新的API?

private static string ConnectionString = "mongodb://user:[email protected]: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>; 

但是,我得到一個「空對象」的錯誤。有什麼問題?

編輯:如果使用新API沒有那麼重要,那就告訴我。

+0

你的GetMyItemCollectionDB方法做了很多....哪一位返回null – Alex

+0

那麼,第一個工程..我不明白爲什麼第二個不工作。你能解釋爲什麼嗎?和可能的解決方案 – Earlee

回答

1

要獲得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); 

是有4版本2.0.0+方式

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

如果你可以擴展它(精心製作),它真的會讓你的答案更有用。 –

0

我相信你知道你的第二個代碼最後退貨IMongoCollection<ItemEntity>

但是,MongoCollection不會繼承自IMongoCollection,這就是爲什麼最後得到NULL值。

相關問題