0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kailash
  • 1
  • 1

2 Answers2

0

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

  • Hi @Yonatan, Thanks for your suggestion In addition to your suggestion i have also done the below in the startup class ``` BsonClassMap.RegisterClassMap(cm => { **cm.MapProperty(c => c.id);** cm.MapProperty(c => c.parameter); cm.MapProperty(c => c.remarks); cm.MapProperty(c => c.value); }); ``` – Kailash Jul 19 '22 at 05:08
  • Did you add your actual `_id`? Maybe try adding `[BsonIgnoreExtraElements]` – Yonatan Rubin Jul 19 '22 at 05:14
0

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

Kailash
  • 1
  • 1