【问题标题】:.NET Framework and Entity Framework Core: How can I get hold of the connection string.NET Framework 和 Entity Framework Core:如何获取连接字符串
【发布时间】:2020-02-21 07:59:40
【问题描述】:

我在 .NET Framework 4.7.2 类库中安装了 EF Core。这只是一个包含一些特定功能的项目,而不是解决方案中的StartUp 项目。然后主项目引用带有 EF Core 的项目,web.config 和 IoC 设置所在的位置。解决方案是针对网站。

根据this page,支持.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 尚未被读取。我需要能够为不同的环境指定不同的连接字符串。

关于如何从&lt;appSettings&gt;&lt;connectionStrings&gt; 获取连接字符串的任何想法?

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

【问题讨论】:

  • @JoelDharansingh 我很想注入连接字符串,但正如我忘记提到的,我无法注入 DbContext。似乎 IoC 尚未初始化。我编辑了这篇文章现在提到这一点。

标签: c# .net entity-framework-core .net-4.7.2


【解决方案1】:

试试这个:

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

【讨论】:

  • 我不清楚,但我已经尝试过了。它也没有工作。
猜你喜欢
  • 1970-01-01
  • 2018-05-08
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 2021-09-20
  • 2023-03-18
  • 2020-12-07
相关资源
最近更新 更多