本文介绍了插入使用InsertOneAsync新的文档(.NET 2.0驱动程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了.NET API版本:
MongoClient客户端=新MongoClient();
VAR服务器= client.GetServer();
变种DB = server.GetDatabase(富);
变种集合= db.GetCollection< BsonDocument>(巴);
变种文档=新BsonDocument {{_id,1},{×,2}};
collection.Save(文件);
它的工作。
当我使用新的.NET驱动程序2.0:
VAR的客户=新MongoClient(mongodb的://本地主机:27017);
VAR数据库= client.GetDatabase(富);
变种集合= database.GetCollection< BsonDocument>(巴);
变种文档=新BsonDocument {{_id,1},{×,2}};
等待collection.InsertOneAsync(文件);
Refs :
Introducing the 2.0 .NET Driver
I want to ask how to insert a new document using .Net Driver 2.0. Thanks.
[Update 1] I tried to implement :
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);
}
Result : WaitingForActivation. Nothing changed in database. Please help me!
[Update 2 (Solved)] : add tsk.Wait(); It worked ! Thanks this post : How would I run an async Task method synchronously?
解决方案
Your method should be like
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);
}
这篇关于插入使用InsertOneAsync新的文档(.NET 2.0驱动程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!