繁体   English   中英

.NET Framework 和 Entity Framework Core:如何获取连接字符串

[英].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-MigrationRemove-Migration等命令时, AppSettings["ConnectionString"]为空,并且抛出异常。

我认为这是由于应用程序处于“设计模式”,并且尚未读取web.config 我需要能够为不同的环境指定不同的连接字符串。

关于如何从<appSettings><connectionStrings>获取连接字符串的任何想法?

编辑:我还想补充一点,该解决方案将 Structuremap 用于 IoC,并且在包管理器控制台中运行迁移命令时,我无法注入 DbContext。

尝试这个:

var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM