I am using version 2.5
of the official MongoDB C# driver and I am encountering an issue where the IgnoreExtraElementsConvention
is not being useful to me when a document gets deserialized to a POCO object. The exception i get
[snip]
System.FormatException
HResult=0x80131537
Message=Element '_id' does not match any field or property of class MongoDeserialization.Person.
Source=MongoDB.Bson
StackTrace:
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)
[/snip]
However, if I were to use the commented BsonIgnoreExtraElements
decorator on the Person class (and even comment out the convention registry block), i get the desired outcome. So, I am wondering what I am missing with the ConventionRegistry
and IgnoreExtraElementsConvention
in order to make the deserialization process ignore unmapped '_id
' fields in my Person
class. Thanks in advance.
Please find below a ready to run test code to reproduce the problem:
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;
namespace MongoDeserialization
{
//[MongoDB.Bson.Serialization.Attributes.BsonIgnoreExtraElements]
class Person
{
public string FirstName;
public string LastName;
}
class MongoDBPersonReader
{
private IMongoCollection<Person> _collection;
public MongoDBPersonReader(string CollectionName)
{
ConventionRegistry.Register("Ignore _id",
new ConventionPack
{
new IgnoreExtraElementsConvention(true),
},
type => true);
_collection = (new MongoClient("mongodb://localhost:27017/")).GetDatabase("my_db")
.GetCollection<Person>(CollectionName);
}
public List<Person> GetAllPersonsFromCollection()
{
return _collection.Find(FilterDefinition<Person>.Empty).ToList();
}
}
class Program
{
static void Main(string[] args)
{
// Add some test data:
List<InsertOneModel<Person>> list_of_insert_person_operations = new List<InsertOneModel<Person>>();
(new List<Person>
{
new Person { FirstName = "Joe", LastName = "Smith" },
new Person { FirstName = "Tom", LastName = "Smith" },
}).ForEach(p => list_of_insert_person_operations.Add(new InsertOneModel<Person>(p)));
(new MongoClient("mongodb://localhost:27017/")).GetDatabase("my_db")
.GetCollection<Person>("my_collection")
.BulkWrite(list_of_insert_person_operations);
// Actual test for ignoring '_id' during deserialization:
List<Person> persons = (new MongoDBPersonReader("my_collection")).GetAllPersonsFromCollection();
}
}
}
User contributions licensed under CC BY-SA 3.0