c# - 使用 InsertOneAsync (.NET Driver 2.0) 插入新文档

标签 c# asp.net mongodb mongodb-.net-driver mongodb-csharp-2.0

在较旧的 .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

Reading and Writing

我想问一下如何使用 .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/

相关文章:

c# - 使用 C# 在 VisualBrush 中设置图像运行时

c# - 为什么在 C# 接口(interface)名称前加上 “I”

c# - 从字符串创建属性选择器表达式

c# - Unity - 等待 HTTP 请求解析

c# - ASP.Net MVC 如何生成日期列表

c# - 使用 ASP.NET、C# 和 JSON 将事件添加到完整日历

c# - 无法从 JValue 转换为 JObject

python - 如何在Python脚本中编写查询

ruby - 在 Ruby 中,MongoDB 返回一个 BSON::OrderedHash。如何将其转换为 JSON?使用 to_json 会出现 "stack level too deep"错误

java - 聚合结果无法正确映射到 Java 对象