0

I'm making an APIS system in ASP.NET Core 7.0 with Entity Framework using the DDD methodology to create models in the database, but I'm having some difficulties applying the migrations. The Context Data Base is as follows:

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

        public ContextDB(DbContextOptions<ContextDB> options) : base(options)
        {
        }

        public DbSet<BSCEMPRESGRP> TBBSCEMPRESGRP { get; set; }
        
        ...
    }

I created a class to receive data from the database connection and initialize migrations.

 public class ContextFactory : IDesignTimeDbContextFactory<ContextDB>
    {
        public ContextDB CreateDbContext(string[] args)
        {
            var lobjGBLSQLCONEXA = new GBLSQLCONEXA();
            var optionsBuilder = new DbContextOptionsBuilder<ContextDB>();
            optionsBuilder.UseSqlServer(lobjGBLSQLCONEXA.GetSQLConectionConfig());
            return new ContextDB(optionsBuilder.Options);
        }
    }

This method suits me very well in ASP Net Core 3.1 and 5.0 version. When I use these same methods and run migrations in version 7.0, it doesn't return anything to create the migrations file, but it doesn't create the database and tables. Searching I found a solution but not very functional which would be to use EnsureCreated().

        public ContextDB(DbContextOptions<ContextDB> options) : base(options)
        {
            Database.EnsureCreated();
        }

That way when I run migrations it creates the file and creates the database, but when I do the update it shows some error messages. I went back to do some research and found something similar in the link below: text

That Alex Potapchuk says to use EnsureDeleted and EnsureCreated that would solve it, but this causes an inconvenience since it deletes the entire database and creates it again.

I don't know if the connection string can influence something, but it is as follows

"Data Source=192.13.1.20,1433\SQLSRVSP01DB01;Initial Catalog=teste;Integrated Security=False;User ID=sa;Password=**********;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"

1 Answers1

0

Sorry for the delay in responding.

Today researching a little more I managed to find a solution to the problem.

In the ContextDB class include the following line:

  internal static ContextDB CreateContext()
{
    return new ContextDB(new DbContextOptionsBuilder<ContextDB>().UseSqlServer(SQLCONEXA.GetSQLConectionConfig()).Options);
}

And the ContextFactory looks like this:

    public class ContextFactory : IDesignTimeDbContextFactory<ContextDB>
{
    public ContextDB CreateDbContext(string[] args)
    {
        var dbContext = ContextDB.CreateContext();
        dbContext.Database.Migrate();
        return dbContext;
    }
}

That way I was able to apply migrations without needing Database.EnsureCreated();

Thank you very much for taking the time to try to help.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31