How to enable Migrations using Entity Framework Core = Windows Forms C#

Asked

Viewed 306 times

1

I am testing EF Core in a Windows Forms project following the DDD standard. In the repository layer I created my context and in my domain I already have the Models classes defined. How do I enable Migrations in EF Core and so I don’t have to create each migration manually and keep giving the updates? He wanted Migrations to be enabled and I only gave the update-database...

public class PersistContext : DbContext
    {
        public PersistContext()
        {
        }

        public PersistContext(DbContextOptions<PersistContext> Options)
            :base(Options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ForSqlServerUseIdentityColumns();
            modelBuilder.HasDefaultSchema("SistemaComercial");

            PessoaTipoMap(modelBuilder);
        }

        public DbSet<PessoaTipo> PessoaTipo { get; set; }

        private void PessoaTipoMap(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PessoaTipo>(pt =>
            {
                pt.ToTable("tblPessoaTipo");

                pt.HasKey(ptk=> ptk.PessoaTipoId);
                pt.Property(ptp => ptp.PessoaTipoId)
                            .ValueGeneratedOnAdd();//Checar se o auto incremento funciona.

                pt.Property(ptp => ptp.Descricao)
                            .HasColumnName("Descricao")
                            .HasColumnType("Varchar")
                            .HasMaxLength(25)
                            .IsRequired();
            });
        }
    }

 public class FactoryPersistContext : IDbContextFactory<PersistContext>
    {
        private string ConnectionString = ConfigurationManager.ConnectionStrings["SistemaComercial"].ConnectionString;

        public PersistContext Create(DbContextFactoryOptions options)
        {
            var constructor = new DbContextOptionsBuilder<PersistContext>();
            constructor.UseSqlServer(ConnectionString);
            return new PersistContext(constructor.Options);
        }
    }

1 answer

5

This option does not exist in Entity Framework Core.

You can do something similar by making the migration happen whenever the application is started, for development purposes.

Possibly if I were to use this option I would still do some checking to make sure that the application is actually in development mode, but as I do not know the context I will not comment on this

Put this snippet in the application startup code (probably on Startup.cs)

using (var contexto = new Contexto())
{
    contexto.Database.Migrate();
}

Browser other questions tagged

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