Recently I took another look at MongoDb, the document database that’s been around for quite a while. Now there’s a (really good) official C# driver. Coupled with third party LINQ support and some pretty damn good documentation, and I don’t see much reason to use NoRm or any other the other homegrown MongoDb .Net drivers.

One thing that stuck out to me was that there’s no implicit convention using the mapping capabilities to set the collection name for a given class type. Which, if you’re using generic repositories and you only have a System.Type, leaves you with the only option of hardcoding them (bad) or basing them off of the type’s Name or FullName (less bad). I wasn’t thrilled with either option so I wrote some extension methods to make them definable in the same manor as your class maps if you’re using BsonClassMap. Check it:

    public static class BsonClassMapExtensions
{
private static ConcurrentDictionary<Type, string> _cache = new ConcurrentDictionary<Type, string>();

public static string GetCollectionName(this BsonClassMap classMap)
{
string result = null;

if (_cache.TryGetValue(classMap.ClassType, out result))
return result;
else
return classMap.ClassType.Name;
}

public static void SetCollectionName(this BsonClassMap classMap, string collectionName)
{
if (string.IsNullOrEmpty(collectionName))
throw new InvalidOperationException("Collection name must be valid string.");

_cache[classMap.ClassType] = collectionName;
}
}
Now I can specify collection names as so:
            if (BsonClassMap.IsClassMapRegistered(typeof(Blog)) == false)
{
BsonClassMap.RegisterClassMap<Blog>(cm =>
{
cm.AutoMap();
cm.MapIdProperty(x => x.Id);
cm.SetCollectionName("Blogs");
}
);
}

And in my Mongo infrastructure/unit of work/repository implementation I can use

BsonClassMap.LookupClassMap(typeof(Blog)).GetCollectionName();

when necessary and it just works. Nice.
top