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

.net-core entity-framework-core

Question

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

1
2
5/29/2019 3:19:17 PM

Popular Answer

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);
        }
    }
}
1
5/29/2019 3:42:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow