I\'m using mongDb with MongoDrive, I wonder how I can implement to all my classes the [BsonIgnoreExtraElements].
I know there is a way through the <
Use the SetIgnoreExtraElementsConvention
method (from the Conventions section of the C# Driver Serialization Tutorial):
var myConventions = new ConventionProfile();
myConventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention()));
BsonClassMap.RegisterConventions(myConventions, (type) => true);
The parameter (type) => true
is a predicate depending on the class type, that determines whether to apply the convention. So per your requirement it should simply return true regardless; but you could use this to set/exclude the convention on given types if you wanted.
Edit
Per Evereq's comment, the above is obsolete. Now use:
var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);
Basically,
mongoDB affords you the ability to store documents within a single collection that can each have their own schema. This is a drastic change if you have a background in relational databases. In a relational database, you have a static schema per table and you cannot deviate from without changing the structure of the table. In the example below, I have defined a Person class and a PersonWithBirthDate class which derives from the Person class. These can both be stored in the same collection in a mongoDB database. In this case, assume the documents are stored in the Persons collection.
See the sample code -
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonWithBirthDate : Person
{
public DateTime DateOfBirth { get; set; }
}
Now , You can easily retrieve and of the documents and have the mongoDB C# Driver deserialze the document into the PersonWithBirthDate class. However, you will run into issues if you query the Persons collection and try to have the driver deserialize the data into the Person class. You will receive an error that there are elements that cannot be deserialized. This easily fixable by adding the [BsonIgnoreExtraElements] attribute to the Person class. You can see the modified class below. This will instruct the driver to ignore any elements that it cannot deserialize into a corresponding property. With the attribute any document in the Persons collection can be deserailized to the Person class without error.
[BsonIgnoreExtraElements]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonWithBirthDate : Person
{
public DateTime DateOfBirth { get; set; }
}
I hope this will clear your understanding.