使用C#驱动程序从mongodb的数据检索 [英] Retrieve data from mongodb using C# driver
问题描述
我使用C#MongoDB的官方驱动程序在我的测试项目,我已经插入从C#Web应用程序MongoDB的文档。在蒙戈控制台,db.blog.find()可以显示我已经插入条目。但是,当我试图找回它们,.NET抛出一个异常
I'm using official mongodb driver for c# in my test project and i've already insert document from c# web application to mongodb. In mongo console, db.blog.find() can display entries I've inserted. but when i tried to retrieve them, .net throw a exception
System.InvalidOperationException:当CurrentBsonType是字符串,而不是当CurrentBsonType是ReadString只能叫的ObjectId。
我的实体类是非常简单的。
my entity class is very simple
namespace MongoDBTest
{
public class Blog
{
public String _id
{
get;
set;
}
public String Title
{
get;
set;
}
}
}
这是我的检索码
and this is my retrieve code
public List<Blog> List()
{
MongoCollection collection = md.GetCollection<Blog>("blog");
MongoCursor<Blog> cursor = collection.FindAllAs<Blog>();
cursor.SetLimit(5);
return cursor.ToList();
}
任何人可以帮助我吗?谢谢!
can anybody help me out? thanks!
推荐答案
我想你只需要标记你的博客标识与 BsonId
(插入ID自己)属性:
I suppose you just need mark your blog Id with BsonId
(and insert id yourself) attribute:
public class Blog
{
[BsonId]
public String Id {get;set;}
public String Title{get;set;}
}
和所有应该没问题。问题是,因为你没有标明哪一个领域将是MongoDB的_id和驱动程序生成_id字段类型的ObjectId。 ,而当司机试图反序列化回来,他不能转换的ObjectId为String
And all should be okay. Issue was because you not marked what field will be Mongodb _id and driver generated _id field with type ObjectId. And when driver trying deserialize it back he can't convert ObjectId to String.
完整的例子:
MongoCollection collection = md.GetCollection<Blog>("blog");
var blog = new Blog(){Id = ObjectId.GenerateNewId().ToString(),
Title = "First Blog"};
collection .Insert(blog);
MongoCursor<Blog> cursor = collection.FindAllAs<Blog>();
cursor.SetLimit(5);
var list = cursor.ToList();
这篇关于使用C#驱动程序从mongodb的数据检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!