Create Database without Migration in Entity Framework Core

Asked

Viewed 890 times

1

I am developing a study application in Entity Framework Core, and saw that through code-first it is possible to generate the database using the add-on commandMigration, but I wonder if there is any way the application create the database without the 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.

1 answer

3

Yes, it is possible!

EPH

1 - Dbcontext startup, runs before instantiating 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);

http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx

https://msdn.microsoft.com/en-us/data/jj591621


EF Core

In the case of EF Core Voce you need to do the following configuration on your Startup.Cs or on your context initializer.

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 to check if all Migrations have been applied and then create the Seed method by 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 boot using Migrate and then do 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();
}
            }
  • But that would be for the Entity Framework Core?

  • In the case of EF Core vc you can context.Database.Migrate().

  • updated the example, see if it helps you! :)

  • To take 10, you can add sample first data Seed?

  • @Thiagolunardi sincerely do not know if it is the most appropriate way, but what I do is an extension method to validate if everything was migrated successfully then do the Migrate and Seed.

  • Yes, if it is the first creation, it is the system relying on initial/minimum data to work, it is the most suitable. Ex. In the first run of Wordpress, it creates a default admin user and a Default category.

  • @Thiagolunardi take a look at the example, it’s just an idea!

  • Show! That’s how it’s done!!!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.