2015-09-30 37 views
0

我想将文档保存到集合中,我的方法如下,但根本不存储。无法使用.Net驱动程序2.0保存mongodb c#中的文档

internal static void InitializeDb() 
    { 
     var db = GetConnection(); 
     var collection = db.GetCollection<BsonDocument>("locations"); 
     var locations = new List<BsonDocument>(); 
     var json = JObject.Parse(File.ReadAllText(@"..\..\test_files\TestData.json")); 
     foreach (var d in json["locations"]) 
     { 
      using (var jsonReader = new JsonReader(d.ToString())) 
      { 
       var context = BsonDeserializationContext.CreateRoot(jsonReader); 
       var document = collection.DocumentSerializer.Deserialize(context); 
       locations.Add(document); 
      } 
     } 
     collection.InsertManyAsync(locations); 
    } 

如果我做了异步并等待,那么它最近运行,我需要先运行这个,然后只测试数据。

+0

你必须等待“InsertManyAsync”的方法。 –

+0

谢谢,明白了 – veshu

回答

1

以供将来参考,wait()在异步方法工作的结束就像同步

internal static void InitializeDb() 
{ 
    var db = GetConnection(); 
    var collection = db.GetCollection<BsonDocument>("locations"); 
    var locations = new List<BsonDocument>(); 
    var json = JObject.Parse(File.ReadAllText(@"..\..\test_files\TestData.json")); 
    foreach (var d in json["locations"]) 
    { 
     using (var jsonReader = new JsonReader(d.ToString())) 
     { 
      var context = BsonDeserializationContext.CreateRoot(jsonReader); 
      var document = collection.DocumentSerializer.Deserialize(context); 
      locations.Add(document); 
     } 
    } 
    collection.InsertManyAsync(locations).wait(); 
} 
相关问题