Reputation: 683
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.
Upvotes: 1
Views: 1409
Reputation: 11
Try this:
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
Upvotes: 1