我正在学习 Mongo DB C#driver 用法。我跟着文档https://docs.mongodb.com/getting-started/csharp/insert/和InsertOneAsync
代码示例引发了异常,如下所示:
System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
Additional information: The type initializer for 'TestMongo.Program' threw an exception.
这是我的代码文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace TestMongo
{
class Program
{
protected static IMongoClient _client = new MongoClient();
protected static IMongoDatabase _database = _client.GetDatabase("test");
static void Main(string[] args)
{
InsertOneDocument();
}
static async Task InsertOneDocument()
{
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
}
}
}
我在 .Net 4.5 框架上使用 CSharpDriver-2.4.3 驱动程序。有人可以帮我解决一下这个问题吗?
答案 0 :(得分:0)
您的代码没有任何问题,但您没有等待执行
只需更改主要方法并停用项目中的CLR Exception
,看看它是否只是first chance exception
static void Main(string[] args)
{
InsertOneDocument().GetAwaiter().GetResult();
}
答案 1 :(得分:0)
你得到的错误是因为这一行:
protected static IMongoClient _client = new MongoClient();
将其更改为此应该可以正常工作:
var connectionString = "mongodb://localhost";
protected static IMongoClient _client = new MongoClient(connectionString);