简体   繁体   中英

.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. 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.

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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