Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialization Error ASP.NET MongoDB

I am trying to retireve all the documents in my MongoDB collection via a REST api built in ASP.NET MVC 4 and I have encoutered an error when i enter localhost:50491/api/document:

An error occurred while deserializing the Id property of class Acord_Rest_API.Models.Document: Cannot deserialize string from BsonType ObjectId.

My controller looks like:

public class DocumentController : ApiController
{
    public readonly MongoConnectionHelper<Document> docs;

    public DocumentController()
    {
        docs = new MongoConnectionHelper<Document>();
    }

    public IList<Document> getAllDocs()
    {
        var alldocs = docs.collection.FindAll();
        return alldocs.ToList();
    }
}

My MongoDB document looks like this? enter image description here

What am I missing here?

My class that connects to the DB:

public class MongoConnectionHelper<T> where T: class
{
    public MongoCollection<T> collection { get; private set; }

    public MongoConnectionHelper()
    {
        string connectionString = "mongodb://127.0.0.1";
        var server = MongoServer.Create(connectionString);
        if (server.State == MongoServerState.Disconnected)
        {
            server.Connect();
        }
        var conn = server.GetDatabase("Acord");
        collection = conn.GetCollection<T>("Mappings");
    }
}

EDIT here is my solution: enter image description here

MongoConnectionHelper does the connection to the DB, DocumentController has the methods to retrive all the documents and Document contains what you have suggested in your answer.

EDIT here is the Document class:

[DataContract]
public class Document
{
    public ObjectId _id { get; set; }

    [DataMember]
    public string MongoId
    {
        get { return _id.ToString(); }
        set { _id = ObjectId.Parse(value); }
    }
    public IList<string> alldocs { get; set; }
}
like image 726
Mike Barnes Avatar asked Dec 11 '22 18:12

Mike Barnes


1 Answers

A more simple approach is to tell MongoDB to treat string field as ObjectId. You can do it easily by using BsonType attribute.

[BsonRepresentation(BsonType.ObjectId)]
public string _id { get; set; }
like image 135
Ofir Avatar answered Jan 01 '23 10:01

Ofir