コンソールの.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; }
}
この方法が失敗する理由はありますか?
'DbContext'の派生クラス内で' OnConfiguring'メソッドをオーバーライドする – maclaud
DbContextと 'DbContextOptions'オプションを強く結合しても大丈夫なら' OnConfiguring'はいいです:) – gldraphael