I have the following setup that works but when the MongoDB Collection has extra field then the program crash with error
"System.FormatException: Element 'FriendName' does not match any field or property of class MyApp.User"
I am under the impression that the MongoDB driver is able to map only the fields that is declared in C# Class. Is there a way around this ? Thank you.
MongoDB - Collection User
{ Name: "Allen" , Age: 22, Address: "Sample Address", FriendName = "Sue"}
public class User
{
public string Name {get;set;}
public int Age {get; set;}
public string Address {get;set; }
}
_db.GetCollection<User>("User").Find(f => f.Name == "Allen").FirstOrDefault();
MongoDB C# driver expects that all fields in your BSON document match your .NET class - that's the default behavior. You can change that using BsonIgnoreExtraElements attribute
[BsonIgnoreExtraElements]
public class User
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
I also found a way to globally set the BsonIgnoreExtraElements by call the following ConventionPack before accessing the DB.
var conventionpack = new ConventionPack() { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionpack, type => true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With