Created
March 21, 2013 22:15
-
-
Save craiggwilson/5217295 to your computer and use it in GitHub Desktop.
Convention to automatically persist string identifiers as ObjectId's in MongoDB.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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