Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GuidRepresentation.Standard with MongoDB

I am implementing a custom IBsonSerializer with the official MongoDB driver (C#). I am in the situation where I must serialize and deserialize a Guid.

If I implement the Serialize method as follow, it works:

public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
    BsonBinaryData data = new BsonBinaryData(value, GuidRepresentation.CSharpLegacy);
    bsonWriter.WriteBinaryData(data);
}

However I don't want the Guid representation to be CSharpLegacy, I want to use the standard representation. But if I change the Guid representation in that code, I get the following error:

MongoDB.Bson.BsonSerializationException: The GuidRepresentation for the writer is CSharpLegacy, which requires the subType argument to be UuidLegacy, not UuidStandard.

How do I serialize a Guid value using the standard representation?

like image 328
Flavien Avatar asked May 04 '13 00:05

Flavien


2 Answers

Old question but in case someone finds it on google like I did...

Do this once:

BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;

For example, in a Web Application/Web API, your Global.asax.cs file is best place to add it once

public class WebApiApplication : System.Web.HttpApplication
{
   protected void Application_Start()
   {
      BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;

      //Other code...below

   }
}
like image 193
Peter Avatar answered Nov 01 '22 01:11

Peter


If you don't want to modify the global setting BsonDefaults.GuidRepresentation (and you shouldn't, because modifying globals is a bad pattern), you can specify the setting when you create your collection:

IMongoDatabase db = ???;
string collectionName = ???;
var collectionSettings = new MongoCollectionSettings {
  GuidRepresentation = GuidRepresentation.Standard
};
var collection = db.GetCollection<BsonDocument>(collectionName, collectionSettings);

Then any GUIDs written to the collection will be in the standard format.

Note that when you read records from the database, you will get a System.FormatException if the GUID format in the database is different from the format in your collection settings.

like image 38
meustrus Avatar answered Nov 01 '22 01:11

meustrus