Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core Migration error: "Unable to create an object of type 'ApplicationContext'"

I'm trying to do the migration with EF Core but I get an error - how can I fix this error?

PM> add-migration ini

Unable to create an object of type 'ApplicationContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

like image 808
Maria Perez Avatar asked Jul 14 '18 20:07

Maria Perez


2 Answers

I had the same issue with asp.net core 3.1. For me, it was pretty straight forward, adding an implementation of IDesignTimeDbContextFactory to the main web project fixed the issue.

A basic implementation looks something like this:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
    public YourDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<YourDbContext >();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        return new YourDbContext(builder.Options);
    }
}

Please refer to this blog post on the subject.

like image 180
SamTh3D3v Avatar answered Sep 17 '22 19:09

SamTh3D3v


This will also happen if you have multiple start-up projects - when migrating, just select one (in VS right click Solution and Set StartUp Projects...)

like image 20
john hunter Avatar answered Sep 20 '22 19:09

john hunter