Search code examples
mongodbasp.net-coremongodb-.net-driver

.Net Core MongoDB.Driver ObjectId Null from POCO Mapping


I am working with ASP.net Core, MongoDB.Driver 2.13.0, and a MongoDB document with the following structure:

 "lrec80" : [ 
    {
        "RR4NFAD" : {
            "$ref" : "RR4OCO",
            "$id" : ObjectId("00000000000000008c8a414b"),
            "$db" : "tpfdf"
        },
        "RR4NRCC" : 43,
        "RR4NAKY" : 0,
        "RR4NA80" : {
            "RR4NSDT" : { "$binary" : "UOE=", "$type" : "00" }
        },
        "RR4NPDT" : { "$binary" : "UOs=", "$type" : "00" },
        "RR4NTY1" : -124,
        "RR4NCTY" : "IAH",
        "RR4NLIA" : null,
        "RR4NNBR" : 1
    }, 

My POCO objects maps almost all the fields I need, with the exception of the "RR4NFAD" object.

public class RR4NFAD
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public ObjectId Id { get; set; }

    [BsonElement("$ref")]
    public string Ref { get; set; }

    [BsonElement("$db")]
    public string DB { get; set; }
}

If I set Id property to ObjectId type, I get the DB and Ref fields successfully, but Id field shows the following:

Id = {000000000000000000000000}
CreationTime = 1/1/1970 12:00:00 AM
Increment = 0
Machine = 0
Pid = 0
Timestamp = 0

If I set Id field to string:

   public class RR4NFAD
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonElement("$ref")]
    public string Ref { get; set; }

    [BsonElement("$db")]
    public string DB { get; set; }
}

Id returns as null, but I still get the DB and Ref fields successfully

I've tried creating a ObjectIdConverter without success and applying it as an attribute on the Id field using the following example:

Returning ObjectID as a string from ASP.NET Core

How can I get the RR4NFAD Id field to return as one of the following as a reference to query another document?

  • ObjectId("00000000000000008c8a414b")
  • "00000000000000008c8a414b"

Thanks for any help you can offer. Seems like a simple problem, but I'm new to MongoDB and it's giving me fits.


Solution

  • Issue & Concern

    According to MongoDB forum's comment from James_Kovacs,

    The .NET/C# driver automatically adds an _id member if you don’t assign one explicitly. The driver automatically maps the Id property of a class to the _id field in the database. You can override this with class mapping attributes or code configuration if desired.

    This is why your Id in RR4NFAD class will not able to get the value as it is being translated to _id instead of Id.


    Solution

    Implement the Class Map to override the default behavior of Id member.

    BsonClassMap.RegisterClassMap<RR4NFAD>(cm =>
    {
        cm.AutoMap();
        cm.UnmapProperty(c => c.Id);
        cm.MapMember(c => c.Id)
            .SetElementName("$id");
    });
    

    Demo

    enter image description here