Enterprise Framework

Software Solutions in the Enterprise

ASP.NET Core - Entity Framework - Code First Add-Migration - Unable to resolve service for type Microsoft.EntityFrameworkCore.Migrations.IMigrator.

Entity Framework Error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Migrations.IMigrator'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

Solution:

Verify the connectionstring in the appsettings.json file.

{
  "ConnectionStrings": {
    "CustomerDb":  "Server=(localdb)\\mssqllocaldb;Database=Customer;Trusted_Connection=True;"
  }
}
On Startup.cs, ConfigureService method, verify, you are correctly initializing the Context

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("CustomerDb")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }


Comments are closed