Created
September 28, 2017 10:38
-
-
Save ksysiekj/daea97345e4ae4388db7b34a1be89156 to your computer and use it in GitHub Desktop.
This file contains 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
public static class EntityTypeConfigurationExtensions | |
{ | |
private static readonly MethodInfo EntityMethod = typeof(ModelBuilder).GetTypeInfo().GetMethods().Single(x => x.Name == "Entity" && x.IsGenericMethod && x.GetParameters().Length == 0); | |
private static readonly IDictionary<Assembly, IEnumerable<Type>> TypesPerAssembly = new Dictionary<Assembly, IEnumerable<Type>>(); | |
private static Type GetEntityType(Type type) | |
{ | |
Type interfaceType = type.GetInterfaces().First(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)); | |
return interfaceType.GetGenericArguments().First(); | |
} | |
private static ModelBuilder ApplyConfiguration<T>(this ModelBuilder modelBuilder, IEntityTypeConfiguration<T> configuration) where T : class | |
{ | |
Type entityType = GetEntityType(configuration.GetType()); | |
dynamic entityTypeBuilder = EntityMethod | |
.MakeGenericMethod(entityType) | |
.Invoke(modelBuilder, new object[0]); | |
configuration.Map(entityTypeBuilder); | |
return modelBuilder; | |
} | |
private static readonly Assembly CurrentAssembly = typeof(AdventureWorksDbContext).Assembly; | |
public static ModelBuilder UseEntityTypeConfiguration(this ModelBuilder modelBuilder) | |
{ | |
IEnumerable<Type> configurationTypes; | |
if (!TypesPerAssembly.TryGetValue(CurrentAssembly, out configurationTypes)) | |
{ | |
TypesPerAssembly[CurrentAssembly] = configurationTypes = CurrentAssembly | |
.GetExportedTypes() | |
.Where(x => x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))); | |
} | |
IEnumerable<dynamic> configurations = configurationTypes.Select(Activator.CreateInstance); | |
foreach (dynamic configuration in configurations) | |
{ | |
ApplyConfiguration(modelBuilder, configuration); | |
} | |
return modelBuilder; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment