Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

ef code first - How to get file path in Entity Framework Seed method without HttpContext (executed from package manager command)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")))

Additionally, to debug the Seed method I like to just throw an Exception with the message I want to display (I'm a beginner in EF, I haven't figured out how to write to the NuGet Package manager console yet :))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...