user1615476
user1615476

Reputation: 161

MongoDB C# driver and MVC4 webapi. Issue in json serialization

I am using MongoDB database with MVC4 WebAPI using the C# driver provided by MongoDB. I have a an issue with serialization. I get the following error,

    "ExceptionMessage=Error getting value from '__emptyInstance' on 'MongoDB.Bson.ObjectId'"

If I change the Content-Type to xml in my HTTP request it just works fine. I would appreciate any help.

I have copied the model below.

public class Subscriber
{
    public ObjectId _id;

    public long SubscriberId { get; set; }

    public Name Name { get; set; }

    public Address Address { get; set; }

    public string Phone { get; set; }

    public ICollection<Subscription> Subscription { get; set; }


    public Subscriber()
    {
        Name = new Name();
        Address = new Address();
        Subscription = new Collection<Subscription>();
}
}

Solution

Converting _id type string and decorating the field as below did the trick

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string _id;

reference: JSON.NET cast error when serializing Mongo ObjectId

Upvotes: 2

Views: 2446

Answers (1)

Illuminati
Illuminati

Reputation: 4619

For anyone trying the mentioned "solution" in the answer : It simply doesn't work!

Check the marked answer in this, instead.

Upvotes: 1

Related Questions