Retrieve data from mongodb using C# driver

北战南征 提交于 2019-12-05 18:16:27

问题


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!


回答1:


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;}
}

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:

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();



回答2:


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

  1. List
  2. Cursor
  3. linq

    using (var cursor = await col.Find(new BsonDocument()).ToCursorAsync())
    {
     while (await cursor.MoveNextAsync())
     {
        foreach (var doc in cursor.Current)
        {
            Console.WriteLine(doc);
        }
      }
    }
    

the above code Shows to retrieve the data using cursors. Referrence




回答3:


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.




回答4:


The type and name of the id member should be different as follows

public ObjectId Id { get; set; }

Where ObjectId is in the namespace MongoDB.Bson



来源:https://stackoverflow.com/questions/6772261/retrieve-data-from-mongodb-using-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!