Use GuidRepresentation.Standard with MongoDB

guid, mongodb, mongodb-.net-driver

Solution

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

   }
}

Problem

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?

Original source