Problem
When I try to add a migration to my code, e.g: dnx ef migrations add initial
,
the env.WebRootPath
in Startup(IHostingEnvironment env)
is null.
This will give me compilation errors when adding a new migration or updating the database.
The Code
In the Startup.cs class I have these lines in the constructor:
public Startup(IHostingEnvironment env)
{
// ...
MyStaticClass.Initialize(env.WebRootPath);
// ...
_hostingEnvironment = env;
}
Here env.WebRootPath
is null and in the Initialize
function this throws an exception.
In the ConfigureServices function of the Startup.cs I resolve my class dependencies:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddInstance<IMyService>(new MyService(_hostingEnvironment.WebRootPath))
// Note: _hostingEnvironment is set in the Startup constructor.
// ...
}
Notes
I can build, run, and deploy the code fine. Everything works!
However I made a change in the model and want to add a migration with this command: dnx ef migrations add MyMigration
then I see the compilation errors in the package manager console.
I am using ASP 5 web application, and Entity Framework 7
To summarize, here's the distinction between the two root paths: The content root path is the absolute path to the directory that contains the application content files. The web root path is the absolute path to the directory that contains the web-servable application content files.
The IHostingEnvironment is an interface for . Net Core 2.0. The IHostingEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller. The IHostingEnvironment interface have two properties.
The env.WebRootPath can also be null if the wwwroot folder has been inadvertantly removed from the root of your project. Adding a wwwroot folder to the root of your project will also fix this issue.
There is an issue reported on github regarding my problem:
https://github.com/aspnet/EntityFramework/issues/4494
I used the workaround in the comments now it seems to be working fine:
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With