Home > Net >  Property with name "id" not deserialized in mongodb C#
Property with name "id" not deserialized in mongodb C#

Time:07-19

I am trying to fetch a record from the mongo db in c#

Data in the mongodb collection:

{
  id:0
  parameter:"Unscheduled Demand"
  remarks:"Formula Based"
  value:89
}

Issue: id property is not getting deserialized from the data in C#.

C# class structure:

public class children
{
    [BsonId]
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

This is the error that occurs:

Element 'id' does not match any field or property of class children

CodePudding user response:

According to the documentation here https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/ the [BsonId] attribute defines which field should be mapped for Mongo's _id element. If you want to use a field called "id" you should remove this tag

public class children
{
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

My guess is that without removing the attribute you will still be able to insert into Mongo, and see there is an _id set

CodePudding user response:

We need to make manually identify the identity property as per the official mongodb documentation for C#

https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/

Changes Made

Previous Class Structure

public class children
{
    [BsonId]
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

Current Class Structure

public class children
{
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

Additional Changes in

Startup.cs

BsonClassMap.RegisterClassMap<children>(cm =>
            {
                cm.MapProperty(c => c.id);
                cm.MapProperty(c => c.parameter);
                cm.MapProperty(c => c.remarks);
                cm.MapProperty(c => c.value);
            });

MAKING THE ABOVE CHANGES RESOLVED MY ISSUE

  • Related