0

I'm following this get started tutorial with .net core (2.0): https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db

But when I run the command:

Add-Migration InitialCreate

I get the response:

Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory<MyContext>' to the project
trees_are_great
  • 3,881
  • 3
  • 31
  • 62

1 Answers1

0

The error basically tells you, that u have no class implementing the IDesignTimeDbContextFactory.

To solve this issue create a class implements the interface, that could look like following:

public class Foo : IDesignTimeDbContextFactory<MyContext> {
  //Add interface methods here
}

That should solve the issue, because then u have your class Foo which implements this interface, which seems to be necessary.

Option2

If that does not help in any case, please check if your class "MyContext" inherits from DbContext.

Your class should look like the following:

public class MyContext : DbContext {
//some stuff here
}

Option3

You may have missed to edit your Startup.cs The tutorial tells you to add the following into your Startup.cs file in order to register your context

// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;";
    services.AddDbContext<MyContext>(options => options.UseSqlServer(connection));
}
Tobias Theel
  • 3,088
  • 2
  • 25
  • 45
  • The first method moved me onto another error. The interface requires that I have ' public MyContext CreateDbContext(string[] args)' implemented as a method. I am not sure how to implement this: public MyContext CreateDbContext(string[] args) { return new MyContext(null); } the options cannot be null. I have triple checked points 2 and 3 – trees_are_great Aug 27 '17 at 14:42
  • I created another project from scratch and it worked. hmm – trees_are_great Aug 27 '17 at 14:53
  • 1
    If u find out. what was wrong, post it as your own answer, so others that may face the same issue get an answer :) – Tobias Theel Aug 27 '17 at 15:29
  • yeah, it was a duplicate - i needed to add something to the main class. – trees_are_great Aug 27 '17 at 17:03