I am attempting to set up an EntityFrameworkCore.DbContext in a new project. My DbContext will live in a class library referenced by my AspNetCore Web Api project. I'm trying to register the context as a service in the ConfigureServices method of Startup.cs, as follows
services.AddDbContext<DataContext>(options => options.UseMySql(Configuration.GetConnectionString("MySql")));
I have verified in appsettings.json file, my connection string is under ConnectionStrings.MySql. The constructor for my DbContext that should be used and receiving the options is here
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
However, if I try to run dotnet ef migrations add Initial
, the build fails, citing a required parameterless constructor. If I add a parameterless constructor and try to add migrations again, I instead get this error
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
Since I definitely have a constructor that accepts DbContextOptions and passes it to the base constructor, I am left with configuring it via the OnConfiguring method, like
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySql(connectionString);
}
}
But now the problem becomes that I need the connection string from the Web Api project's app settings.json file to be passed to the class library where the DbContext lives. I have tried referencing similar questions here, but have been unsuccessful in finding and implementing solution. The accepted answer here and the top upvoted answer here looked very promising, but I was unable to figure out how to adapt them to my situation.