Asp.net-Core
使用 EF7 命令時,IHostingEnvironment.WebRootPath 為空
問題
當我嘗試向我的程式碼添加遷移時,例如:
dnx ef migrations add initial,
env.WebRootPathin為Startup(IHostingEnvironment env)空。添加新遷移或更新數據庫時,這會給我帶來編譯錯誤。
程式碼
在Startup.cs類中,我在建構子中有這些行:
public Startup(IHostingEnvironment env) { // ... MyStaticClass.Initialize(env.WebRootPath); // ... _hostingEnvironment = env; }這
env.WebRootPath是 null 並且在Initialize函式中拋出異常。在Startup.cs的**ConfigureServices函式中,我解決了我的類依賴項:
public void ConfigureServices(IServiceCollection services) { // ... services.AddInstance<IMyService>(new MyService(_hostingEnvironment.WebRootPath)) // Note: _hostingEnvironment is set in the Startup constructor. // ... }筆記
- 我可以很好地建構、執行和部署程式碼。一切正常!
- 但是,我對模型進行了更改,並希望使用此命令添加遷移:
dnx ef migrations add MyMigration然後我在包管理器控制台中看到編譯錯誤。- 我正在使用 ASP 5 Web 應用程序和 Entity Framework 7
github上報告了一個關於我的問題的問題:
<https://github.com/aspnet/EntityFramework/issues/4494>
我在評論中使用了解決方法,現在它似乎工作正常:
if (string.IsNullOrWhiteSpace(_env.WebRootPath)) { env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"); }
如果 wwwroot 文件夾被無意中從項目的根目錄中刪除,則 env.WebRootPath 也可以為空。將 wwwroot 文件夾添加到項目的根目錄也可以解決此問題。