[英]How to get file path in Entity Framework Seed method without HttpContext (executed from package manager command)
In my entity framework Seed method I have the following line to get a file from a different project: 在我的实体框架Seed方法中,我有以下代码行可以从其他项目中获取文件:
var filePath = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath).Parent.FullName + "\\Com.ProjectX\\companies.xls";
This works when a HttpContext is available, like when using this action method to trigger it: 这在HttpContext可用时有效,例如使用以下操作方法触发它时:
public ActionResult About()
{
var configuration = new Com.EntityModel.Configuration();
var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
migrator.Update();
return View();
}
However, it doesn't work when I execute Update-Database
from the package manager console (the file isn't found and it's hard to debug because I also can't breakpoint when doing that. 但是,当我从程序包管理器控制台执行Update-Database
时,它不起作用(找不到文件,并且很难调试,因为这样做时我也无法断点。
I'd like to be able to use Update-Database command and have it work without an HttpContext. 我希望能够使用Update-Database命令并使它在没有HttpContext的情况下工作。 How can I get the path? 我怎么走?
I use this function to map paths inside the Seed method, not very clean but it works: 我使用此函数来映射Seed方法内部的路径,虽然不是很干净,但是可以工作:
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")))
Additionally, to debug the Seed method I like to just throw an Exception with the message I want to display (I'm a beginner in EF, I haven't figured out how to write to the NuGet Package manager console yet :)) 此外,要调试Seed方法,我只想对要显示的消息抛出Exception(我是EF的初学者,我还没有弄清楚如何写到NuGet程序包管理器控制台:))
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 :(
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.