我在 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);
}
}
如果在运行update-database时,数据库不存在且需要创建,则在Core 2.0中需要此项操作。
升级到ASP.NET Core 2.0后无法创建迁移
我希望不要在这里和appsettings.json两个地方都有ConnectionString,而只在.json文件中存在,所以我尝试替换了
"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
withConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
但它不起作用,我得到了空值。更新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")));
}
}
但是我无法在ToDoContextFactory中使用这个,因为它没有 Configuration,而且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);
}
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
添加到您的ConfigurationBuilder
中。您是否已经这样做了?'普通'应用程序设置是否正常工作? - Jan_VSystem.AppContext.BaseDirectory
来获取基本路径,如果您无法在启动时执行此操作,则可以参考@borisdj的建议:https://github.com/aspnet/Announcements/issues/237。 - William ArdilaSetBasePath
来自哪里的人:https://dev59.com/HVYN5IYBdhLWcg3w07Fx#46843572;而`AddJsonFile`来自哪里:https://dev59.com/sF4c5IYBdhLWcg3w7t7E - Adam Houldsworth