我是新来的在C#中使用mongo数据库,但我想在mongo数据库中导入大型数据库。 MyDb包含仅具有简单参数Id,Body,Title Tags的实体。mongodb C#异常无法反序列化BsonType字符串Int32
这是mongo中的实体示例。
{
"Id" : "someff asdsa",
"Title" : "fsfds fds",
"Body ": "fsdfsd fs",
"Tags" : "fsdfdsfsd"
}
这是我在C#类mongoEntity的
[BsonIgnoreExtraElements]
class Element
{
[BsonId]
public ObjectId _id { get; set; }
[BsonElement("Id")]
public string Id { get; set; }
[BsonElement("Title")]
public string Title { get; set; }
[BsonElement("Body")]
public string Body { get; set; }
[BsonElement("Tags")]
public string Tags { get; set; }
public void ShowOnConsole()
{
Console.WriteLine(" _id {0} Id {1} Title {2} Body {3} Tags {4} ", _id, Id, Title, Body, Tags);
}
}
这是我的主要方法的代码
const string connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase database = server.GetDatabase("mydb");
MongoCollection<Element> collection = database.GetCollection<Element>("train");
Console.WriteLine("Zaimportowano {0} rekordow ", collection.Count());
MongoCursor<Element> ids = collection.FindAll();
foreach (Element entity in ids)
{
entity.ShowOnConsole();
}
当我运行这段代码,我能够看到一些数据,但我有例外 “无法从BsonType Int32反序列化字符串”。 我认为其中一个属性在数据库中表示为int,但我不知道如何处理它?一个实体中的一个属性是int,而另一个对象中的同一个属性是string? 我需要做什么来读取所有数据库?
非常感谢你的回复! – Konrad
不客气。另见第二种方法,也许它会更好。 – Shad
太棒了。方法2是我的首选方法。谢谢! –