oleksii
3/21/2013 - 10:15 PM

Convention to automatically persist string identifiers as ObjectId's in MongoDB.

Convention to automatically persist string identifiers as ObjectId's in MongoDB.

using System.Diagnostics;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Driver;

namespace ConsoleApplication1
{
    class Program
    {
        private class Foo
        {
            public string Id { get; set; }
        }


        static void Main(string[] args)
        {
            var pack = new ConventionPack();
            pack.Add(new StringObjectIdConvention());
            ConventionRegistry.Register("MyConventions", pack, _ => true);


            // just to prove it works...

            var client = new MongoClient();
            var testDb = client.GetServer().GetDatabase("test");
            var fooCol = testDb.GetCollection<Foo>("foo");
            fooCol.Drop();

            fooCol.Save(new Foo());

            var fooColBson = testDb.GetCollection("foo");
            var fooDoc = fooColBson.FindOne();

            Debug.Assert(fooDoc["_id"].IsObjectId);
        }

        private class StringObjectIdConvention : ConventionBase, IPostProcessingConvention
        {
            public void PostProcess(BsonClassMap classMap)
            {
                var idMap = classMap.IdMemberMap;
                if (idMap != null && idMap.MemberName == "Id" && idMap.MemberType == typeof(string))
                {
                    idMap.SetRepresentation(BsonType.ObjectId);
                    idMap.SetIdGenerator(new StringObjectIdGenerator());
                }
            }
        }
    }
}