实体框架 - 如何获得种子的方法相对文件路径 [英] Entity Framework - How to get relative file path in seed method
问题描述
为什么是文件路径为空?如何获取相对文件路径任何想法?
Why is filePath null? Any ideas on how to get the relative filePath?
internal sealed class Configuration : DbMigrationsConfiguration<MvcProject.Models.FileDb>
{
public Configuration()
{
// code here is not relevant to question
}
protected override void Seed(MvcProject.Models.FileDb context)
{
string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/File.txt");
// read File.txt using filePath and update the database
}
}
我在Configuration.cs文件上面code在迁移时的实体框架是建立在ASP .NET MVC项目创建的文件夹
I have the above code in Configuration.cs file in Migrations folder created when entity framework is set up on an ASP .NET MVC project
当我运行程序包管理器控制台更新,数据库-Verbose我得到一个错误的文件路径为null。
When I run "Update-Database -Verbose" in Package Manager Console I get an error that filePath is null.
如果我手动设置文件路径以绝对URL到文件中:
If I manually set filePath with an absolute URL to the file:
string filePath = "C:/Users/User1/My Documents/Visual Studio 2012/Projects/MvcProject/Content/File.txt";
一切工作正常。
Everything works fine.
显然,目标是有相对路径,以使对不同的设置不同的开发工作。
Obviously the goal is to have a relative path to enable work with different developers on different setups.
说实话我需要的是文件 - 不一定的路径。任何帮助将AP preciated。
Truth be told all I need is the file - not necessarily the path. Any help will be appreciated.
推荐答案
我用这个功能来种子方法中映射路径,不是很干净,但它的工作原理:
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")))
这篇关于实体框架 - 如何获得种子的方法相对文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!