Accessing context inside Up in DbMigration

I am trying to migrate my db based on my data in my current db. I am having a hard time querying the db to grab information to allow me to do this. My ideal solution would look like

public partial class Reset: DbMigration
{
    public override void Up()
    {
        string SqlCmd = "my query";
        if(Execute(SqlCmd) > 5)
        {
            //do this migration
        }
    }
}

      

So I have a problem getting data back during the migration.

Edit

Many of you guys have wondered why I need this, so I'll give you guys some nasty details.

Since our project has grown, so has the db migration history. We have over 200 rows in our migration history table. We split up the db and did some maintenance here and there to the point where doing all migrations from scratch with an empty db will result in an error as some tables haven't been created yet. Yes, this is a huge mess and that's why I wanted to clean it up. I came across this post on SO before resetting migrations to clean list.I didn't use the accepted answer because the mess of migration we have won't let this work. Thus, the second highest answer was used. The only problem with this chosen solution was that for every developer on your team you will need to point them to instructions to update their db or download the latest version. They cannot do

update-database 

      

purely. So to let them update and make it free for everyone, I would like to query the migration history table, see if there is any mess, and if so, delete the entire history and skip the actual migration, but still populate the migration row in the table.

+3


source to share


2 answers


If you really want to do what you are looking for, you can do T-SQL in your migration, for example:

public partial class Reset: DbMigration
{
    public override void Up()
    {
        Sql(@"
            DECLARE @result int
            SELECT @result = <query>

            IF (@result > 5)
            BEGIN
                <migration stuff>
            END");
    }
}

      



... or some changes to this.

Please note: DropColumn conditionally during migration

+3


source


The context can't be created until after the migration is applied, so you won't be able to access it. You can use normal ADO.NET methods to query the database.

What I would recommend is to put the code in your Seed method in the database initializer. The seed runs after every migration and is a suitable place to maintain the database during migration. You can just create a blank migration and then in Seed check if the conditions are correct to do what you want to do.



It might help if you explain more specifically what you are trying to do.

+1


source







All Articles