Add-Migration fails with Dependency injection in console core 2.0 app

.net-core c# entity-framework-core

Question

I try to use EF Core 2.0 in a console .net core 2.0 application. When i either use IDesignTimeDbContextFactory or override OnConfiguring method of a DbContext derived class CustomerDbContext, then Add-Migration is successfull in package manager console. But if i try to use AddDbContext like in an asp.net core application, i receive the message:

Unable to create an object of type 'CustomerDbContext'

The code snippet for console .net core application is:

class Program
{

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        IConfigurationRoot config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")     //needs Microsoft.Extensions.Configuration.Json
            .Build();

        string conn = config.GetConnectionString("WarehouseConnection");
        services
            .AddDbContext<CustomerDbContext>(
            options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));

        var provider = services.BuildServiceProvider();
        using(var context = provider.GetService<CustomerDbContext>())
        {
             ...   
        }

    }

}

the config.json contains the connection string:

{
  "ConnectionStrings": {
    "WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}

the CustomerDbContext class is:

class CustomerDbContext : DbContext   
{
    public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }
    public DbSet<Customer> Customers { get; set; }
}

Any ideas why this approach fails?

1
0
5/28/2018 7:09:49 PM

Accepted Answer

Starting from 2.0, the EF tool checks for a BuildWebHost() method and uses it to access application services if it exsits. Since you don't need a BuildWebHost() using IDesignTimeDbContextFactory is the right approach.

Check the announcement and this comment in the discussion for more information.

2
12/8/2017 3:57:20 PM

Popular Answer

So you need to implement IDesignTimeDbContextFactory interface. Add a class that implements this interface inside of your project.

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public CustomerDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<CustomerDbContext>();
        var connectionString = configuration.GetConnectionString("WarehouseConnection");
        builder.UseSqlServer(connectionString);

        return new CustomerDbContext(builder.Options);
    }
}

For more info read Cannot make migration. ef core 2.0



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