Skip to content

Instantly share code, notes, and snippets.

@jordanyaker
Created September 20, 2013 21:05
Show Gist options
  • Save jordanyaker/6643891 to your computer and use it in GitHub Desktop.
Save jordanyaker/6643891 to your computer and use it in GitHub Desktop.

The following code should be added to your context by overriding the OnModelCreating function:

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
#if DEBUG
            using (MiniProfiler.Current.Step("DataContext.OnModelCreating")) { 
#endif
                base.OnModelCreating(modelBuilder);

                var addMethods = typeof(ConfigurationRegistrar).GetMethods()
                    .Where(m => m.Name.Equals("Add"))
                    .ToList();

                var entityTypeMethod = addMethods.First(m =>
                    m.GetParameters()
                     .First()
                     .ParameterType
                     .GetGenericTypeDefinition()
                     .IsAssignableFrom(EntityType));

                var complexTypeMethod = addMethods.First(m =>
                    m.GetParameters().First()
                     .ParameterType
                     .GetGenericTypeDefinition()
                     .IsAssignableFrom(ComplexType));

                var types = typeof(DataContext).Assembly
                    .GetExportedTypes()
                    .Where(IsMappingType)
                    .ToList();

                foreach (var type in types) {
                    MethodInfo typedMethod;
                    Type modelType;

                    if (IsMatching(type, out modelType, t => EntityType.IsAssignableFrom(t))) {
                        typedMethod = entityTypeMethod.MakeGenericMethod(modelType);
                    } else if (IsMatching(type, out modelType, t => ComplexType.IsAssignableFrom(t))) {
                        typedMethod = complexTypeMethod.MakeGenericMethod(modelType);
                    } else {
                        continue;
                    }

                    typedMethod.Invoke(modelBuilder.Configurations, new[] { Activator.CreateInstance(type) });
                }
#if DEBUG
            } 
#endif
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment