Yes, it is possible!
EF
1 - Initialization of the DBContext, executed before instantiating the Context.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourDbContext, YourMigrationConfiguration>());
2 - Configuration class
public class YourMigrationConfiguration<TContext> : DbMigrationsConfiguration<TContext>
where TContext : DbContext{
protected YourMigrationConfiguration() {
AutomaticMigrationsEnabled = true; // Executa sem esperar os comandos do PM
AutomaticMigrationDataLossAllowed = true;
}
3 - Context.Database.Initialize (true);
link
link
EF Core
For EF Core you need to make the following configuration in your Startup.cs or in the initializer of your context.
public class DBInitialization
{
public static void Initialize()
{
using (var context = new DbContext())
{
context.Database.Migrate();
// Other db initialization code.
}
}
}
EF Core - First Data Seed
I create an extension class with 2 methods, the first one to check if all Migrations have been applied and then create the Seed method checking if each Entity to be initialized is empty and then enter the necessary information.
public static class ContextExtensions
{
public static bool MigrationsApplied(this DbContext context)
{
var applied = context.GetService<IHistoryRepository>()
.GetAppliedMigrations()
.Select(m => m.MigrationId);
var total = context.GetService<IMigrationsAssembly>()
.Migrations
.Select(m => m.Key);
return !total.Except(applied).Any();
}
public static void Seed(this DbContext context)
{
if (!context.Model1.Any())
{
var model = new Model1 { Name = "Teste" };
context.Add(model);
context.SaveChanges();
}
if (!context.Status.Any())
{
var status = new Status { Name = "Ativo" };
context.AddRange(stati);
context.SaveChanges();
}
}
}
In the Startup file in the Configure method, I start the application by applying Migrate and then do the Seed.
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
if (!serviceScope.ServiceProvider.GetService<MyContext>().MigrationsApplied())
{
serviceScope.ServiceProvider.GetService<MyContext>().Database.Migrate();
serviceScope.ServiceProvider.GetService<MyContext>().Seed();
}
}