[英].NET Framework and Entity Framework Core: How can I get hold of the connection string
I've installed EF Core in a .NET Framework 4.7.2 class library.我已经在 .NET Framework 4.7.2 类库中安装了 EF Core。 This is just a project containing some specific functionality, not the
StartUp
project in the solution.这只是一个包含某些特定功能的项目,而不是解决方案中的
StartUp
项目。 The project with EF Core is then referenced by the main project, where the web.config
and IoC setup lives.然后,带有 EF Core 的项目被主项目引用,其中
web.config
和 IoC 设置存在。 The solution is for a web site.解决方案是针对网站。
According to this page , .NET Framework 4.7.2 is supported.根据此页面,支持 .NET Framework 4.7.2。
The problem is injecting or otherwise fetching the connection string, or probably any other configuration/appsettings value.问题在于注入或以其他方式获取连接字符串,或者可能是任何其他配置/应用设置值。
Let's say this is my DbContext
class:假设这是我的
DbContext
类:
public class PersonContext : DbContext
{
public DbSet<Person> Persons { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
if (ConfigurationManager.AppSettings["ConnectionString"] == null)
{
throw new Exception("Hey!");
}
optionsBuilder.UseSqlServer(ConnectionString);
}
}
}
When I run commands like Add-Migration
or Remove-Migration
, the AppSettings["ConnectionString"]
is null, and the exception gets thrown.当我运行
Add-Migration
或Remove-Migration
等命令时, AppSettings["ConnectionString"]
为空,并且抛出异常。
I think this is due to the application being in "design mode", and the web.config
hasn't been read.我认为这是由于应用程序处于“设计模式”,并且尚未读取
web.config
。 I need to be able to specify different connection strings for different environments.我需要能够为不同的环境指定不同的连接字符串。
Any ideas to how I can get the connection string from either the <appSettings>
or the <connectionStrings>
?关于如何从
<appSettings>
或<connectionStrings>
获取连接字符串的任何想法?
Edit: I also want to add that the solution uses Structuremap for IoC, and I can't inject into the DbContext when running the migration commands in the package manager console.编辑:我还想补充一点,该解决方案将 Structuremap 用于 IoC,并且在包管理器控制台中运行迁移命令时,我无法注入 DbContext。
尝试这个:
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.