【发布时间】:2018-01-29 12:12:45
【问题描述】:
我在 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);
}
}
这在 Core 2.0 中是必需的,当数据库不存在时需要迁移,并且必须在运行 update-database 时创建。
Unable to create migrations after upgrading to ASP.NET Core 2.0
我不想在 2 个地方(这里和 appsettings.json)有 ConnectionString,但只在 .json 所以我试图替换
"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
与
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
但它不起作用,我得到的是空值。
更新 1:
请注意,在 Core 2 中不需要显式添加 .json,因此问题不在于文件。
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/
更新 2:
此外,我已经在使用 Configuration 将 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);
}
【问题讨论】:
-
不知道最新版本,但在早期版本中,您仍然需要将
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)添加到您的ConfigurationBuilder。你做过吗? “正常”应用程序设置是否正常工作? -
在 Core2.0 中这是自动完成的:andrewlock.net/…
-
在 Core2.0 中,您可以使用
System.AppContext.BaseDirectory获取基本路径,以防您在启动时无法做到这一点,如提及 @borisdj:github.com/aspnet/Announcements/issues/237 -
对于那些想知道
SetBasePath来自哪里的人:stackoverflow.com/questions/46843367/… 和AddJsonFile来自哪里:stackoverflow.com/questions/27382481/… -
谢谢!我认为您应该在解决方案中发布单独的答案,而不是将其嵌入到您的问题中。
标签: c# asp.net-core connection-string appsettings