Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Mongo BsonSerializer.Deserialize Ignore elements that do not exist

Tags:

c#

mongodb

Is there a flat that will tell the C# Mongo BsonSerializer to ignore elements that do not exist in the poco class

Example collection

Animal {"Type" : "Cat", "Skill" : "Jump"}
Animal {"Type" : "Dog", "Skill" : "Bark", "Owner" : "Jimmy"}

If the cat C# class only has

public string Type {get;set;}
public string Skill {get;set;}

When I attempt to execute the following

 var test = BsonSerializer.Deserialize<Animal>(result);

The first item will work fine, the second one will throw an exception that Owner does not exist.

like image 435
Chadit Avatar asked Dec 06 '25 16:12

Chadit


1 Answers

Use [BsonIgnoreExtraElements] attribute on Cat class.
From attribute summary:

Specifies whether extra elements should be ignored when this class is deserialized.

like image 70
FireAlkazar Avatar answered Dec 09 '25 10:12

FireAlkazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!