Skip to content

Instantly share code, notes, and snippets.

@craiggwilson
Created March 21, 2013 22:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craiggwilson/5217295 to your computer and use it in GitHub Desktop.
Save craiggwilson/5217295 to your computer and use it in GitHub Desktop.
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());
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment