Iris Classon
Iris Classon - In Love with Code

Mongo DB Fileformat Exception, the BsonIgnoreElements attribute and the ConventionRegistry

It has been a while since I last used MongoDB, it was first year of school and Daniel- one of the second year students- was talking highly of it. I spent a few days trying it, but had to use SQL Server for the school project. Two years later I join Compare the Market and where we use MongoDB for parts of the system. I’m surprised and impressed how much the C# driver has evolved and know I’m in for some learning which I’ll share on the blog, but keep in mind that I am by no means a routined MongoDB dev.

Let’s talk about the exceptions. The file format exception in particular. If you insert an object and at a later point retrieve it but the type has changed and therefore the two do not match you will get an exception.

An unhandled exception of type ‘System.IO.FileFormatException’ occurred in MongoDB.Driver.dll

Element X does not match any field or property of class MongoDB.TheType

To deal with this you have a few options. If you generally want or expect the the retrieved item to match the domain object you can use the [BsonIgnoreExtraElements] attribute on the class.

[BsonIgnoreExtraElements]

public class Device

{

public ObjectId Id { get; set; }

public string RegistrationNumber { get; set; }

//public string Name { get; set; }

}

However, you might want that to be the default, in other words ignore extra elements on all the classes. This can be achieved by using the ConventionRegistry, by simply passing in a convention that extra elements should be ignored.

You might have done this earlier by using the ConventionProfile

This has however changed, and the way you do it now is like the example below.

var conventions = new ConventionPack { new IgnoreExtraElementsConvention(true) };

ConventionRegistry.Register(“IgnoreExtraElements”, conventions, _ => true);

 

The conventionpack lets you pass in a collection of conventions, and there are many to choose between.

If you don’t certain properties or fields to be serialized in the first place you can ignore them by using some of the ignore attributes on the field or property. Out of the box you get three attributes, one that ignores it regardless, [BsonIgnore], one that ignores it if the value matches the default value [BsonIgnoreIfDefault], or if null, [BsonIgnoreIfNull].

Of course, this is what you get out of the box so these are not limitations. Expect more on MongoDB as I learn more myself :)

 

 

Comments

Leave a comment below, or by email.


Last modified on 2014-09-04

comments powered by Disqus