在较旧的 .Net API 版本中:
MongoClient client = new MongoClient();
var server = client.GetServer();
var db = server.GetDatabase("foo");
var collection = db.GetCollection<BsonDocument>("bar");
var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
collection.Save(document);
成功了。
当我使用新的 .Net Driver 2.0 时:
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("foo");
var collection = database.GetCollection<BsonDocument>("bar");
var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
await collection.InsertOneAsync(document);
Error : The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
引用:
Introducing the 2.0 .NET Driver
我想问一下如何使用 .Net Driver 2.0 插入新文档。谢谢。
[更新 1] 我尝试实现:
public class Repository
{
public static async Task Insert()
{
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("foo");
var collection = database.GetCollection<BsonDocument>("bar");
var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
await collection.InsertOneAsync(document);
}
}
static void Main(string[] args)
{
Task tsk = Repository.Insert();
tsk.Wait();
Console.WriteLine("State: " + tsk.Status);
}
结果:WAITING激活。数据库中没有任何变化。请帮我!
[更新 2(已解决)]:添加 tsk.Wait();有效 ! 感谢这篇文章:How would I run an async Task method synchronously?
最佳答案
你的方法应该是这样的
public async void Insert()
{
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("foo");
var collection = database.GetCollection<BsonDocument>("bar");
var document = new BsonDocument { { "_id", 1 }, { "x", 2 } };
await collection.InsertOneAsync(document);
}
关于c# - 使用 InsertOneAsync (.NET Driver 2.0) 插入新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29599412/