我在 NET Core2.0 应用程序中有以下课程。
// 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);
}
}
当数据库不存在且必须在运行时创建时,Core 2.0 中需要进行迁移更新数据库.
升级到 ASP.NET Core 2.0 后无法创建迁移
我不希望在 2 个地方(此处和 appsettings.json 中)有 ConnectionString,而只在 .json 中
所以我尝试更换
"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
with
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
但它不起作用,我得到了空值。
更新1:
请注意,在 Core 2 中不需要显式添加 .json,因此问题不在于该文件。
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/
更新2:
另外,我已经使用配置将 ConnectionString 从 .json 发送到 Context:
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")));
}
}
但我不能用这个ToDoContextFactory因为它没有配置,并且ToDoContextFactory由迁移使用,因此应用程序根本不运行。
解决方案:
根据@JRB 的回答,我让它像这样工作:
public AppContext CreateDbContext(string[] args)
{
string projectPath = AppDomain.CurrentDomain.BaseDirectory.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0];
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(projectPath)
.AddJsonFile("appsettings.json")
.Build();
string connectionString = configuration.GetConnectionString("DefaultConnection");
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer(connectionString);
return new AppContext(builder.Options);
}