I use MongoDB Driver in my .NET Core application. I will add data model classes as follows:
namespace Test.Database
{
public class DocumentFields
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("account_id")]
public string AccountId { get; set; }
[BsonElement("document_types")]
public DocumentType[] DocumentTypes { get; set; }
[BsonElement("document_themes")]
public DocumentTheme[] DocumentThemes { get; set; }
[BsonElement("created_at")]
public DateTime CreatedAt { get; set; }
}
public class DocumentType
{
[BsonElement("id")]
public string id { get; set; }
[BsonElement("name")]
public string name { get; set; }
}
public class DocumentTheme
{
[BsonElement("id")]
public string id { get; set; }
[BsonElement("name")]
public string name { get; set; }
}
}
But when I try to fetch the data using this model class, it gives this error.
System.FormatException: An error occurred while deserializing the DocumentThemes property of class Test.Database.DocumentFields: Element 'id' does not match any field or property of class Test.Database.DocumentTheme.
The document I'm trying to access is something like this.
{
"_id" : ObjectId("6234410f0f4dd20dd96fb9dd"),
"account_id" : "96f35500-584e-4db9-94cd-ebd93cce13b7",
"created_at" : ISODate("2022-03-18T08:21:35.695+0000"),
"document_themes" : [
{
"id" : "6ad3eac9-e44c-4fdd-b54a-f0ff9165ba3e",
"name" : "Theme 1"
},
{
"id" : "2dd625f2-de57-41f7-9d89-a0e28c62dc65",
"name" : "Theme 2"
},
{
"id" : "af3347c7-12cc-421a-8945-65ce80bf8a0f",
"name" : "Theme 3"
}
],
"document_types" : [
{
"id" : "c0934926-9e1d-468c-9a47-97a62d83228d",
"name" : "Type 1"
},
{
"id" : "331ad071-7d91-4b84-bdf1-733f9868b979",
"name" : "Type 2"
},
{
"id" : "630bbcad-34ec-4b4d-84e4-89724bd8ae17",
"name" : "Type 3"
}
]
}
How I can overcome this obstacle?
Late to the answer.
Similar to this question, the .NET/C# driver will bind the property id
/ Id
/ _id
to the _id
field in the document.
Solution 1
Implement the class map to override the default behavior of id
property.
BsonClassMap.RegisterClassMap<DocumentType>(cm =>
{
cm.AutoMap();
cm.UnmapField(x => x.id);
cm.MapMember(x => x.id)
.SetElementName("id");
});
BsonClassMap.RegisterClassMap<DocumentTheme>(cm =>
{
cm.AutoMap();
cm.UnmapField(x => x.id);
cm.MapMember(x => x.id)
.SetElementName("id");
});
Demo
Solution 2
Apply [BsonNoId]
attribute to the DocumentType
and DocumentTheme
classes to suppress the default Id
behavior.
[BsonNoId]
public class DocumentType
{
...
}
[BsonNoId]
public class DocumentTheme
{
...
}
Demo