Make ‘dotnet ef‘ work with EF Core 2.0

EF Core 2.0 changed the way the CLI looks for the DBContext to use.

There are now two ways:

  • Invoke BuildWebHost in Startup.cs
  • Use the class implementing IDesignTimeDbContextFactory<T>

BuildWebHost is called even if a class implements IDesignTimeDbContextFactory<T>.

Solution for this problem: Rename BuildWebHost to e.g. _BuildWebHost (making it private isn’t enough).

Next step: create the class DesignTimeDbContextFactory:

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

When running dotnet ef database update you will get an error because “appsettings.json” isn’t found.

Set the file’s property Copy to output directory in Visual Studio to “Copy if newer” and it will be copied to the output directory and thus will be found when running any dotnet ef command.

image

Comments

Popular posts from this blog

Debugging Lua scripts in VS Code using MoonSharp

Testing the response body of middleware in ASP.NET Core

Creating a basic MVC 6 web application with Entity Framework 7 and xUnit - Part 2