2

In my entity framework Seed method I have the following line to get a file from a different project:

 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:

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.

I'd like to be able to use Update-Database command and have it work without an HttpContext. How can I get the path?

4

2 回答 2

5

我使用这个函数来映射 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;
}

然后只需使用以下命令调用它:

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

此外,为了调试 Seed 方法,我喜欢只抛出一个带有我想要显示的消息的异常(我是 EF 的初学者,我还没有弄清楚如何写入 NuGet 包管理器控制台:))

于 2013-11-19T11:28:48.020 回答
0
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 :(
}
于 2016-09-07T13:52:17.343 回答