Error while Add-Migration ef core 2 preview 1

c# entity-framework-core

Question

I'm trying to do a sample on ef core 2 but I'm getting the following when I try to add migrations

PM> Add-Migration InitialCreate
No parameterless constructor was found on 'ToDoContext'. Either add a parameterless constructor to 'ToDoContext' or add an implementation of 'IDbContextFactory<ToDoContext>' in the same assembly as 'ToDoContext'.

I followed this tutorial https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db Here is my code.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;";
        services.AddDbContext<ToDoContext>(options => options.UseSqlServer(connection));
        services.AddMvc();
    }
}

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

    }
    public DbSet<ToDo> ToDos { get; set; }
}

public class ToDo
{
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Completed { get; set; }
}
1
1
6/20/2017 6:22:38 PM

Accepted Answer

I recommend implementing IDbContextFactory. Here is an example.

class ToDoContextFactory : IDbContextFactory<ToDoContext>
{
    public ToDoContext Create(DbContextFactoryOptions options)
    {
        var serviceCollection = new ServiceCollection()
            .AddLogging();
        new Startup().ConfigureServices(serviceCollection);

        var serviceProvider = serviceCollection.BuildServiceProvider();

        return serviceProvider.GetRequiredService<ToDoContext>();
    }
}

In 2.0, the ASP.NET Core team updated the recommended pattern for building apps. This broke the way the EF Core tools accessed the application's service provider. This lead us to remove the way we invoked Startup.ConfigureService and update it to invoke Program.BuildWebHost instead. This means that any apps upgrading from 1.x to 2.0 will either need to update to the new pattern or implement IDbContextFactory before they can use the 2.0 tools.

2
6/22/2017 3:31:35 PM

Popular Answer

Well, the problem is very clear:

No parameterless constructor was found

So, you need this:

public class ToDoContext : DbContext
{

    public ToDoContext() // this is a parameterless (with no parameters) constructor 
    { }

    public ToDoContext(DbContextOptions<ToDoContext> options) : base(options)
    { }

    public DbSet<ToDo> ToDos { get; set; }
}


Related Questions





Related

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