gpt4 book ai didi

entity-framework - 如何在没有 HttpContext 的情况下获取 Entity Framework 种子方法中的文件路径(从包管理器命令执行)

转载 作者:行者123 更新时间:2023-12-02 21:47:12 25 4
gpt4 key购买 nike

在我的 Entity Framework 种子方法中,我有以下行来从不同的项目获取文件:

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

这在 HttpContext 可用时有效,例如使用此操作方法触发它时:

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

return View();
}

但是,当我从包管理器控制台执行 Update-Database 时,它不起作用(找不到该文件并且很难调试,因为执行此操作时我也无法断点) .

我希望能够使用 Update-Database 命令并让它在没有 HttpContext 的情况下工作。如何获取路径?

最佳答案

我使用这个函数来映射 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 包管理器控制台: ))

关于entity-framework - 如何在没有 HttpContext 的情况下获取 Entity Framework 种子方法中的文件路径(从包管理器命令执行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19323437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com