par*_*ent 2 entity-framework ef-code-first
在我的实体框架中,种子方法我有以下行来从不同的项目中获取文件:
var filePath = new DirectoryInfo(HostingEnvironment.ApplicationPhysicalPath).Parent.FullName + "\\Com.ProjectX\\companies.xls";
Run Code Online (Sandbox Code Playgroud)
这在HttpContext可用时有效,就像使用此操作方法触发它一样:
public ActionResult About()
{
var configuration = new Com.EntityModel.Configuration();
var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
migrator.Update();
return View();
}
Run Code Online (Sandbox Code Playgroud)
但是,当我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;
}
Run Code Online (Sandbox Code Playgroud)
然后使用以下方法调用它:
using (var streamReader = new StreamReader(MapPath("~/Data/MyFile.csv")))
Run Code Online (Sandbox Code Playgroud)
另外,为了调试Seed方法,我喜欢用我想要显示的消息抛出一个Exception(我是EF的初学者,我还没想出如何写入NuGet包管理器控制台:))
| 归档时间: |
|
| 查看次数: |
1487 次 |
| 最近记录: |