Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHostingEnvironment.WebRootPath is null when using EF7 commands

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

like image 502
A-Sharabiani Avatar asked Feb 10 '16 17:02

A-Sharabiani


People also ask

What is Webrootpath?

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.

What is IHostingEnvironment?

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.


2 Answers

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.

like image 80
Ricky Keane Avatar answered Jan 04 '23 08:01

Ricky Keane


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");
}
like image 22
A-Sharabiani Avatar answered Jan 04 '23 10:01

A-Sharabiani