.NET Framework and Entity Framework Core: How can I get hold of the connection string

.net .net-4.7.2 c# entity-framework-core

Question

I've installed EF Core in a .NET Framework 4.7.2 class library. This is just a project containing some specific functionality, not the StartUp project in the solution. The project with EF Core is then referenced by the main project, where the web.config and IoC setup lives. The solution is for a web site.

According to this page, .NET Framework 4.7.2 is supported.

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:

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.

I think this is due to the application being in "design mode", and the web.config hasn't been read. 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>?

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.

1
1
2/21/2020 9:01:08 AM

Popular Answer

Try this:

var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
1
2/21/2020 8:38:56 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow