How to get the file path in the Entity Framework Seed method without HttpContext (executed from the package manager command)

In my Framework Seed method entity, I have the following line to get a file from another project:

var filePath = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath).Parent.FullName + "\\Com.ProjectX\\companies.xls"; 

This works when an HttpContext is available, for example, when using this action method to start it:

 public ActionResult About() { var configuration = new Com.EntityModel.Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); migrator.Update(); return View(); } 

However, this does not work when I execute Update-Database from the package manager console (the file was not found and it is difficult to debug it, because I also cannot stop doing this.

I would like to use the Update-Database command and work without an HttpContext. How can I get the way?

+1
source share
2 answers

I use this function to map paths inside the Seed method, not very clean, but it works:

 private string MapPath(string seedFile) { if(HttpContext.Current!=null) return HostingEnvironment.MapPath(seedFile); var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath; var directoryName = Path.GetDirectoryName(absolutePath); var path = Path.Combine(directoryName, ".." + seedFile.TrimStart('~').Replace('/','\\')); return path; } 

then just call it using:

  using (var streamReader = new StreamReader(MapPath("~/Data/MyFile.csv"))) 

Also, for debugging the Seed method, I like to just throw an exception with the message I want to display (I'm new to EF, I haven't figured out how to write to the NuGet package manager console yet :))

+4
source
 private string GetPath(string relativeFilePath) { var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath; var directoryName = Path.GetDirectoryName(absolutePath); var path = Path.Combine(directoryName, ".." + relativeFilePath.TrimStart('~').Replace('/', '\\')); return System.Web.HttpUtility.UrlDecode(path); // decode spaces in path :( } 
0
source

Source: https://habr.com/ru/post/943804/


All Articles