11
votes

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.

4
What version you currently use for EF core ?user4851087
Make sure that you have selected the default project (which has DBContext) in Package Manager console. And you have selected your host project (which has startup.cs) as the startup project before running the above commandvivek nuna

4 Answers

9
votes

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...)

7
votes

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.

1
votes

It is highly probably because of your default startup project:

Open Package manager console and write this command:

 PM> Add-Migration -StartupProject[YourProjectPath(just press a tab all the.csproj paths will come up, and then choose your DataBaseLayer project to execute a migration for)] migrationName

In this way you don't need to again go to solution and set startup project with your webProject whenever you finished adding a new migration.

0
votes

1.Modify your code in ConfigureService with :

options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),

        x => x.MigrationsAssembly("WebApplication")));
  1. In command line which includes WebApplication.csproj:

dotnet ef migrations add Init