![](/img/trans.png)
[英]how to get connection string in .net core to Azure SQL without Entity Framework?
[英].NET Framework and Entity Framework Core: How can I get hold of the connection string
我已经在 .NET Framework 4.7.2 类库中安装了 EF Core。 这只是一个包含某些特定功能的项目,而不是解决方案中的StartUp
项目。 然后,带有 EF Core 的项目被主项目引用,其中web.config
和 IoC 设置存在。 解决方案是针对网站。
根据此页面,支持 .NET Framework 4.7.2。
问题在于注入或以其他方式获取连接字符串,或者可能是任何其他配置/应用设置值。
假设这是我的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);
}
}
}
当我运行Add-Migration
或Remove-Migration
等命令时, AppSettings["ConnectionString"]
为空,并且抛出异常。
我认为这是由于应用程序处于“设计模式”,并且尚未读取web.config
。 我需要能够为不同的环境指定不同的连接字符串。
关于如何从<appSettings>
或<connectionStrings>
获取连接字符串的任何想法?
编辑:我还想补充一点,该解决方案将 Structuremap 用于 IoC,并且在包管理器控制台中运行迁移命令时,我无法注入 DbContext。
尝试这个:
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.