Skip to content

Instantly share code, notes, and snippets.

@KozzyKoder
Created February 27, 2014 06:31
Show Gist options
  • Save KozzyKoder/9245411 to your computer and use it in GitHub Desktop.
Save KozzyKoder/9245411 to your computer and use it in GitHub Desktop.
Mongodb useful mapping conventions
public class MappingConventions
{
public static void Initialize()
{
var __conventionPack = new ConventionPack()
{
new IgnoreIfNullConvention(true),
new NamedIdMemberConvention("Id"),
new CamelCaseElementNameConvention(),
new NamedExtraElementsMemberConvention("ExtraElements"),
new ReadWriteMemberFinderConvention(),
new IgnoreExtraElementsConvention(false),
new NamedParameterCreatorMapConvention(),
new StringObjectIdIdGeneratorConvention(),
new SimpleIdGeneratorConvention()
};
ConventionRegistry.Register("Conventions",
__conventionPack,
type => type.Namespace != null && (type.Namespace.Contains(".Domain")));
RegisterAllStoredTypes();
}
public static void RegisterAllStoredTypes()
{
var __storedTypes = Assembly.GetAssembly(typeof(Entity))
.GetTypes()
.Where(t => t.IsAbstract == false
&& t.IsGenericType == false &&
typeof(IStoredEntity).IsAssignableFrom(t))
.Where(t => BsonClassMap.IsClassMapRegistered(t) == false);
__storedTypes
.ForEach(t => typeof(BsonClassMap)
.GetMethods()
.First(m => m.Name == "RegisterClassMap" && m.IsGenericMethod)
.MakeGenericMethod(t)
.Invoke(null, null));
}
#region Nested type: SimpleIdGeneratorConvention
public class SimpleIdGeneratorConvention : ConventionBase, IPostProcessingConvention
{
private readonly IPostProcessingConvention _default = new LookupIdGeneratorConvention();
public void PostProcess(BsonClassMap classMap)
{
var __idMemberMap = classMap.IdMemberMap;
if (__idMemberMap != null)
{
if (__idMemberMap.MemberInfo.Name == "Id" && __idMemberMap.MemberInfo.DeclaringType == typeof(string))
__idMemberMap.SetIdGenerator(new StringObjectIdGenerator());
_default.PostProcess(classMap);
}
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment