Create database without Migration in the Entity Framework Core

1

I am developing a study application in Entity Framework Core, and I saw that through code-first it is possible to generate the database using the add-migration command, but I would like to know if there is any way for the application to create the base data without there being any need for me to execute the add-migration and update-database commands.

I would like to do something similar to hibernate, where every time I run the application it updates the base according to the annotations of the entities.

    
asked by anonymous 17.07.2017 / 23:19

1 answer

3

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();
}
            }
    
18.07.2017 / 00:22