你需要一個上下文工廠因此EF核心可以爲遷移創建的DbContext:
public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
private IConfigurationRoot _configuration;
public MyDbContextFactory()
{
var builder = new ConfigurationBuilder()
.SetBasePath(System.AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_configuration = builder.Build();
}
public MyDbContext Create()
{
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"), m => { m.EnableRetryOnFailure(); });
return new MyDbContext(optionsBuilder.Options);
}
}
而一個appsettings.json
文件,你把你的連接字符串:
{
"ConnectionStrings": {
"DefaultConnection": "<your_connection_string>"
}
}
您是否嘗試瞭解錯誤的建議?這似乎是最直接的事情要做。 – mason
請參閱http://benjii.me/2016/05/dotnet-ef-migrations-for-asp-net-core/ point 3 – Milen
@mike如果我嘗試建議我需要將connectionstring添加爲硬編碼。這是你需要避免 – pantonis