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?