5
I am developing an application and the need arose to add Migration and run the update at runtime.
I already have the whole part that loads the modules:
public class ClientContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
LoadModulos();
LoadMaps(modelBuilder);
}
public static void LoadMaps(DbModelBuilder modelBuilder)
{
IEnumerable<Type[]> assemblies = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.FullName.StartsWith("NCode.")
&& a.FullName.Contains(".EF")
&& !a.FullName.Contains("NCode.EF")
&& a.GetTypes().Any(t => t.Namespace != null && t.Namespace.EndsWith(".Map")))
.Select(a => a.GetTypes().Where(t => t.Namespace != null && t.Namespace.EndsWith(".Map")).ToArray());
foreach (var types in assemblies)
{
foreach (var t in types)
{
// Verifica se classe pai do tipo (t) é a EntityTypeConfiguration<>
var entityTypeConfiguration = typeof(EntityTypeConfiguration<>);
var baseType = t.BaseType;
if (!baseType.IsGenericType
&& baseType.IsGenericTypeDefinition
&& !(baseType.GetGenericTypeDefinition() == entityTypeConfiguration))
{
continue;
}
// Tipo da entidade
Type entityType = baseType.GetGenericArguments()[0];
// Método Add da Configuration
MethodInfo method = typeof(ConfigurationRegistrar).GetMethods()
.FirstOrDefault(x => x.Name == "Add" && x.GetGenericArguments()[0].ToString().Equals("TEntityType"));
// Trasforma em um generic method passando o Tipo da Entidade
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { entityType });
// Cria a instancia do Map
object map = (object)Activator.CreateInstance(t);
try
{
// Invoca o generic method passando a configurations a instancia do map
genericMethod.Invoke(modelBuilder.Configurations, new object[] { map });
}
catch (Exception ex)
{
}
}
}
}
private void LoadModulos()
{
NCodeSection configSection = (NCodeSection)
System.Configuration.ConfigurationManager.GetSection("NCode");
foreach (NCodeModuloElement customAssembly in configSection.Modulos)
{
try { Assembly.Load("NCode." + customAssembly.Nome + ".Model"); }
catch (Exception ex) { }
try { Assembly.Load("NCode." + customAssembly.Nome + ".EF"); }
catch (Exception ex) { }
}
}
public ClientContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
Does anyone have any idea how to do?
Looking for something similar for customer updates I found this article that exemplifies the use of Migrations in Runtime: https://romiller.com/2012/02/09/running-scripting-migrations-from-code/
– Danilo Bicas