skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search