How to Add an implementation of 'IDesignTimeDbContextFactory' to the project in c# entity-framework-core


Here are the list of packages which I have installed : Installed Packages

I am using Entityframework core 2.0. First time I have successfully created database using entity framework code first migration(add-migration and update-database command). Now when I update my entities and try to run migration it's giving me following error.

Unable to create an object of type 'DataContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see for additional patterns supported at design time.

Here is my code ...


public static void Main(string[] args)

public static IWebHost BuildWebHost(string[] args) =>


public Startup(IConfiguration configuration)
    Configuration = configuration;

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
    // Repositories

        options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        //options => options.UseSqlServer(@"Server=LAPTOP-518D8067;Database=Gyanstack;Trusted_Connection=True;MultipleActiveResultSets=true"));

    services.AddScoped<ISectionRepository, SectionRepository>();
    services.AddScoped(typeof(IEntityBaseRepository<>), typeof(EntityBaseRepository<>));


public class DataContext : DbContext
    public DataContext(DbContextOptions<DataContext> options) 
        : base(options)
    { }

    public DbSet<Section> Section { get; set; }
    public DbSet<SubSection> SubSection { get; set; }
    public DbSet<Article> Article { get; set; }
    public DbSet<Comment> Comment { get; set; }
    public DbSet<User> User { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        modelBuilder.AddConfiguration(new SectionMap());
        modelBuilder.AddConfiguration(new SubSectionMap());
        modelBuilder.AddConfiguration(new ArticleMap());
        modelBuilder.AddConfiguration(new CommentMap());
6/9/2018 8:37:52 PM

Popular Answer

EDIT: now obsolete. Microsoft updated their migration document at the end of September to show how to update so you do not need this workaround.

As seen on this issue I raised on github, you move your DB initialisation code to the Program main, putting it in between BuildWebHost() and .Run()

Its relatively easy once you understand you need to get the DB context using var context = services.GetRequiredService<MyContext>(); in Main and then everything works as expected. (though I still think DB initialisation is a one-time initialisation thing, not an every-program-run thing)

6/10/2018 11:53:16 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow