Home > OS >  MongoDb C# An error occurred while deserializing the property of class
MongoDb C# An error occurred while deserializing the property of class

Time:10-05

I am trying to retrieve data from local MongoDb with JSON documents like this:

{ 
    "teryt_num_code" : "AB",
    "id": 1,
    "name": "Alabama"
}

I have created a POCO class as following:

public class Sensor
{
    public int id { get; set; }
    public string name { get; set; }
    public string teryt_num_code { get; set; }
}

To retrieve all data from my database I use a method below:

public async Task<ICollection<Sensor>> GetAllAsync() => await _collection.Find(_ => true).ToListAsync();

but the exception was thrown calling that method:

An error occurred while deserializing the property of class Sensor: 
Element 'id' does not match any field or property of class Sensor.

What I am doing wrong?

CodePudding user response:

By default, the id property of your class is mapped to the BSON id (property _id on the document). This leaves the id property in the MongoDB document without a corresponding property in the POCO. Therefore, the error is raised.

In order to fix the deserialization error, you can apply both a BsonNoId and a BsonIgnoreExtraElements attribute to the POCO:

[BsonNoId]
[BsonIgnoreExtraElements]
public class Sensor
{
    public int id { get; set; }
    public string name { get; set; }
    public string teryt_num_code { get; set; }
}

BsonNoId disables the convention; therefore BSON id is mapped to POCO id. BsonIgnoreExtraElements fixes the error that the driver does not know how to deserialize the _id property that every MongoDB document contains.

  • Related