使用 C# 驱动程序从 mongodb 检索数据
我在我的测试项目中使用 C# 的官方 mongodb 驱动程序,并且我已经将文档从 C# Web 应用程序插入到 mongodb。在 mongo 控制台中,db.blog.find() 可以显示我插入的条目。但是当我尝试检索它们时,.net抛出异常
“System.InvalidOperationException:ReadString只能在CurrentBsonType为String时调用,而不是在CurrentBsonType为ObjectId时调用。”
我的实体类非常简单
namespace MongoDBTest
{
public class Blog
{
public String _id
{
get;
set;
}
public String Title
{
get;
set;
}
}
}
,这是我的检索码
public List<Blog> List()
{
MongoCollection collection = md.GetCollection<Blog>("blog");
MongoCursor<Blog> cursor = collection.FindAllAs<Blog>();
cursor.SetLimit(5);
return cursor.ToList();
}
有人可以帮我吗?谢谢!
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: ReadString can only be called when CurrentBsonType is String, not when CurrentBsonType is 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想您只需要使用
BsonId
(并自己插入 id)属性标记您的博客 ID:一切都应该没问题。问题是因为您没有标记哪个字段将是 Mongodb _id 和驱动程序生成的 ObjectId 类型的 _id 字段。当驱动程序尝试将其反序列化时,他无法将 ObjectId 转换为 String。
完整示例:
I suppose you just need mark your blog Id with
BsonId
(and insert id yourself) attribute: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.
Complete example:
推出数据
linq
上述代码显示使用游标检索数据。
参考
Retrieving the data from the MongoDB using C# is pretty simple and there are three different ways the data can be rolled out for frontend
linq
the above code Shows to retrieve the data using cursors.
Referrence
看看我在 github 上的示例项目。最近,我对 MongoDB 变得非常感兴趣。这个应用程序显示了许多您可能也会感兴趣的有用的东西; MongoDB 的存储库模式。
Take a look at my sample project at github. Off late, I've become really interested in MongoDB. This application shows many useful things that might interest you as well; repository pattern with MongoDB.
id 成员的类型和名称应该不同,如下所示
其中
ObjectId
位于命名空间MongoDB.Bson
中The type and name of the id member should be different as follows
Where
ObjectId
is in the namespaceMongoDB.Bson