2017-12-08 23 views
0

コンソールの.netコア2.0アプリケーションでEFコア2.0を使用しようとしました。 IDesignTimeDbContextFactoryを使用するか、派生クラスCustomerDbContextのメソッドOnConfiguringを上書きすると、Add-Migrationがパッケージマネージャコンソールで正常に動作します。しかし、私はasp.netのコアアプリケーションのようにAddDbContextを使用しようとすると、私はメッセージが表示されます。コンソールコア2.0アプリケーションの依存性注入で追加移行が失敗する

Unable to create an object of type 'CustomerDbContext'

をコンソール.NETのコアアプリケーションのためのコードスニペットは、次のとおりです。

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>()) 
     { 
      ... 
     } 

    } 

} 

config.json

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

CustomerDbContextクラスは次のとおりです:接続文字列が含まれてい

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

この方法が失敗する理由はありますか?

答えて

2

を読んBuildWebHost()方法についてEFツールをチェックし、それがexsits場合は、アプリケーションのサービスにアクセスするためにそれを使用しています。あなたはBuildWebHost()を使用する必要がないので、IDesignTimeDbContextFactoryを使用することが適切な方法です。

詳細についてはthe announcementthis comment in the discussionを確認してください。

+0

'DbContext'の派生クラス内で' OnConfiguring'メソッドをオーバーライドする – maclaud

+0

DbContextと 'DbContextOptions'オプションを強く結合しても大丈夫なら' OnConfiguring'はいいです:) – gldraphael

0

したがって、IDesignTimeDbContextFactoryインターフェイスを実装する必要があります。プロジェクトの内部にこのインターフェイスを実装するクラスを追加します。詳細情報については

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); 
    } 
} 

、2.0から始まっCannot make migration. ef core 2.0

+0

はい私はそれを知っています。しかし、私が尋ねるのは、asp.netコアの実装に似ている上記のコードスニペットが失敗する理由です。 – maclaud

関連する問題