我在NET Core2.0 App中有以下类.
// required when local database does not exist or was deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
public AppContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
}
}
Run Code Online (Sandbox Code Playgroud)
当Database不存在时,在Core 2.0中需要进行迁移,并且必须在运行update-database时创建.
升级到ASP.NET Core 2.0后无法创建迁移
我想在2个地方(这里和appsettings.json)没有ConnectionString,但只在.json,所以我试图更换
"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
Run Code Online (Sandbox Code Playgroud)
同
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我得到空值.
更新1:
请注意,在Core 2中明确添加.json是不必要的,所以问题不在于文件.
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/
更新2:
此外,我已经使用Configuration从.json向Context发送ConnectionString:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); …Run Code Online (Sandbox Code Playgroud)