Unable to create migrations after upgrading to ASP.NET Core 2.0

ruhm picture ruhm · Aug 20, 2017 · Viewed 104.5k times · Source

After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.

I'm getting

"An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Cannot open database "..." requested by the login. The login failed. Login failed for user '...'"

and

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

The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..\Web" (from the project/folder with the DBContext).

Connection string: "Server=(localdb)\\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"

This is my Program.cs

 public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();
}

Answer

jaaso picture jaaso · Aug 23, 2017

You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.

Here is the sample code:

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

Then, navigate to your Database project and run the following from command line:

dotnet ef migrations add InitialMigration -s ../Web/

dotnet ef database update -s ../Web/

-s stands for startup project and ../Web/ is the location of my web/startup project.

resource