I'm currently applying the [BsonRepresentation(BsonType.String)]
attribute to all Guid
properties in my domain models to have those properties serialized in string format. Besides being tiresome to do, that doesn't work out sometimes, e.g. with custom Wrapper<T>
classes:
public class Wrapper<T>
{
public T Value { get; set; }
// Further properties / business logic ...
}
When T
is Guid
, the Value
property will be stored as binary data of type UuidLegacy
(as will any property of type Guid
that's not decorated with the above attribute). However, I'd like all Guid
s, including Wrapper<Guid>.Value
, to be represented as a string in the database.
Is there any way to tell the MongoDB C# driver to store all Guid
s in string format?
This can be achieved using Conventions
Something along the lines of:
var myConventions = new ConventionProfile();
myConventions.SetSerializationOptionsConvention(
new TypeRepresentationSerializationOptionsConvention(typeof (Guid), BsonType.String));
BsonClassMap.RegisterConventions(myConventions, t => t == typeof (MyClass));
This should go somewhere in your app startup.
You can read more about conventions here: http://www.mongodb.org/display/DOCS/CSharp+Driver+Serialization+Tutorial#CSharpDriverSerializationTutorial-Conventions