使用EF7命令时IHostingEnvironment.WebRootPath为null [英] IHostingEnvironment.WebRootPath is null when using EF7 commands

查看:1105
本文介绍了使用EF7命令时IHostingEnvironment.WebRootPath为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

当我尝试向代码中添加迁移时,例如:dnx ef migrations add initial

When I try to add a migration to my code, e.g: dnx ef migrations add initial,

Startup(IHostingEnvironment env)中的env.WebRootPath为空.

在添加新的迁移或更新数据库时,这将给我带来编译错误.

This will give me compilation errors when adding a new migration or updating the database.

代码

Startup.cs 类中,我在构造函数中具有以下几行:

In the Startup.cs class I have these lines in the constructor:

public Startup(IHostingEnvironment env)
{
    // ...
    MyStaticClass.Initialize(env.WebRootPath);
    // ...
    _hostingEnvironment = env;
}

此处env.WebRootPath为空,并且在Initialize函数中将引发异常.

Here env.WebRootPath is null and in the Initialize function this throws an exception.

Startup.cs ConfigureServices 函数中,我解决了类依赖项:

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

注释

  • 我可以很好地构建,运行和部署代码.一切正常!

  • I can build, run, and deploy the code fine. Everything works!

但是我对模型进行了更改,并希望使用以下命令添加迁移:dnx ef migrations add MyMigration然后我在包管理器控制台中看到了编译错误.

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.

我正在使用ASP 5 Web应用程序和Entity Framework 7

I am using ASP 5 web application, and Entity Framework 7

推荐答案

在github上有一个关于我的问题的问题报告:

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");
}

这篇关于使用EF7命令时IHostingEnvironment.WebRootPath为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆