S.A*_*.A. 9 c# database asp.net-mvc entity-framework ef-migrations
为什么filePath为null?有关如何获取相对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
}
}
Run Code Online (Sandbox Code Playgroud)
我在ASP .NET MVC项目上设置实体框架时创建的Migrations文件夹中的Configuration.cs文件中有上述代码
当我在包管理器控制台中运行"Update-Database -Verbose"时,我收到一个错误,即filePath为null.
如果我手动设置filePath与文件的绝对URL:
string filePath = "C:/Users/User1/My Documents/Visual Studio 2012/Projects/MvcProject/Content/File.txt";
Run Code Online (Sandbox Code Playgroud)
一切正常.
显然,目标是建立一个相对路径,以便在不同的设置上与不同的开发人员一起工作.
真相被告知所有我需要的是文件 - 不一定是路径.任何帮助将不胜感激.
Wie*_*sma 24
我用这个函数来映射Seed方法里面的路径,不是很干净但是它有效:
private string MapPath(string seedFile)
{
if(HttpContext.Current!=null)
return HostingEnvironment.MapPath(seedFile);
var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; //was AbsolutePath but didn't work with spaces according to comments
var directoryName = Path.GetDirectoryName(absolutePath);
var path = Path.Combine(directoryName, ".." + seedFile.TrimStart('~').Replace('/','\\'));
return path;
}
Run Code Online (Sandbox Code Playgroud)
然后使用以下方法调用它:
using (var streamReader = new StreamReader(MapPath("~/Data/MyFile.csv")))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6532 次 |
| 最近记录: |