繁体   English   中英

Mongo DB C#教程代码不起作用

[英]Mongo DB C# tutorial code not working

我正在学习Mongo DB C#驱动程序用法。 我按照文档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驱动程序。 有人可以给我解决这个问题的办法吗?

您的代码没有任何问题,但是您不等待执行

只需更改您的主要方法并在项目中禁用CLR Exception ,看看它是否只是first chance exception

      static void Main(string[] args)
        {
            InsertOneDocument().GetAwaiter().GetResult();
        }

您收到的错误是由于以下原因:

protected static IMongoClient _client = new MongoClient();

更改为此,它应该工作:

var connectionString = "mongodb://localhost";
protected static IMongoClient _client = new MongoClient(connectionString);    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM