Paulo Abreu
Paulo Abreu

Reputation: 1786

Code first migrations: read sql from file

I following a post from ADO.NET team Code First Migrations: Alpha 3 ‘No-Magic’ Walkthrough

I'm trying to read a file with sql for a migration in a asp.net mvc web application. I'm using sql method. The problem is that no matter what I do I can not get a root path to my project. I always get 'c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\'

Could someone point me a way to open my file?

Thanks.

Edited

public partial class AddMembership : DbMigration
{
    public override void Up()
    {
        //var file = File.OpenText(System.IO.Path.GetDirectoryName() + "Model/Schema/membership-up.sql");
        //var file = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "Model/Schema/membership-up.sql");
        //var path = HttpContext.Current.Request.MapPath("/Models/Schema/membership-up.sql");
        var path = HttpContext.Current.Server.MapPath("/Models/Schema/membership-up.sql");
        Sql(file.ReadToEnd());
    }

    public override void Down()
    {
        // ....
    }
}

Upvotes: 4

Views: 1243

Answers (2)

Eugenio Miró
Eugenio Miró

Reputation: 2428

To run the migration directly from the site you could add this code

var dbMigrator = new DbMigrator(new Settings());
dbMigrator.Update();

To run migrations from either process (IIS vs Package Manager Console) you could check first if Server object is created before using Server.MapPath, this way you'd recognize if you're under IIS or under Package Manager Console. If Server object is null you're under Package Manager Console so you could use something more appropriate to get your current path from like

Directory.GetCurrentDirectory();

So I would replace this code

var path = HttpContext.Current.Server.MapPath("/Models/Schema/membership-up.sql");

with something like this

String path;
if (HttpContext.Current.Server != null) {
    path = HttpContext.Current.Server.MapPath("/Models/Schema/membership-up.sql");
} else {
    path = Path.Combine(Directory.GetCurrentDirectory(), "Models/Schema/membership-up.sql");
}

Upvotes: 0

jdross
jdross

Reputation: 1206

What about using Server.MapPath

http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

Upvotes: 0

Related Questions