Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Error Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time"

I'm creating a ASP .NET Core Web API using VS 2019 preview and .NET Core 3.0. When I try execute : add-migration, I'm getting the error : "Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time,..."

Below is my context file:

  public class AppDbContext : DbContext
  {
     public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        { }
     public DbSet<Categoria> Categorias { get; set; }
     public DbSet<Produto> Produtos { get; set; }
  }

My ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<AppDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

  services.AddControllers().AddNewtonsoftJson();
}

My appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;DataBase....."
  },
...
}

I always using this approach and it works.

I also tried create a empty constructor in context class and the I got this error : "System.InvalidOperationException: No database provider has been configured for this DbContext..."

Am I forgetting some detail ?

note: This works fine in ASP .NET Core 2.2

like image 625
Miriam Estela Siqueira Avatar asked Dec 08 '25 09:12

Miriam Estela Siqueira


1 Answers

You can tell the migration how to create your DbContext by implementing the IDesignTimeDbContextFactory<TContext> interface: If a class implementing this interface is found in either the same project as the derived DbContext or in the application's startup project, the tools bypass the other ways of creating the DbContext and use the design-time factory instead.

for more information see this link

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace MyProject
{
    public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
            optionsBuilder.UseMySql("Server=localhost;DataBase.....");

            return new AppDbContext(optionsBuilder.Options);
        }
    }
}
like image 163
Hadi Avatar answered Dec 10 '25 21:12

Hadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!