Setting up Visual Studio

Create a new Class Library project that will contain all of you migrations and add a reference to the NMigrations.dll assembly.

The initial migration

Your first migration may look like this:

using NMigrations;

[Migration(1)]
public class InitialMigration : IMigration
{
	public void Up(Database db)
	{
		var t = db.AddTable("Customers");
		t.AddColumn("CustomerID", SqlTypes.Int).PrimaryKey().AutoIncrement();
		t.AddColumn("FirstName", SqlTypes.NVarChar, 64).NotNull();
		t.AddColumn("LastName", SqlTypes.NVarChar, 64).NotNull();
	}
	
	public void Down(Database db)
	{
		db.DropTable("Customers");
	}
}

This migrations will create a Table namend "Customers" with three attributes.

Applying the migration

The next step is to apply the migration to your local database. Therefore you use the command line tool "NMigrations.Shell". Open up a command prompt and type:

NMigrations.Shell /assembly XXX /cs "Data Source=.; Integrated Security=True; Initial Catelog=MyDatabase;"

Replace XXX by the name of your class library and adapt the connection string to your local configuration. If you take a look at your database now you will see that two tables have been created: the "Customers" table - just as expected - and a second table called "MigrationHistory". The second table is used by NMigrations to keep track which migrations have already been applied to your database to ensure that migrations are run only once.

The second migration

Add a new class to your migrations class library with the following source:

using NMigrations;

[Migration(2)]
public class InitialMigration : IMigration
{
	public void Up(Database db)
	{
		var t = db.AlterTable("Customers");
		t.AddColumn("Birthday", SqlTypes.Date);
	}
	
	public void Down(Database db)
	{
		var t = db.AlterTable("Customers");
		t.DropColumn("Birthday");
	}
}

This migration will extend your table by a new column. To do so run the NMigrations.Shell command like described above.

Going back

For some reason you may want to got back to your previous version of your database. Run the following command:

NMigrations.Shell /version 1 /assembly XXX /cs "Data Source=.; Integrated Security=True; Initial Catalog=MyDatabase;"

This will execute the "Down" method of your second migration and drop the "Birthday" column.

Testing migrations

If you don't want to mess up your database by invalid migrations, you can take a look at what the migration would do by adding the "/whatif" switch to your command line. This will print out all SQL commands, but won't execute them. You can also add the "/confirm" switch which will make NMigrations to ask for confirmation before executing a SQL statement.

Last edited Sep 15, 2010 at 9:16 AM by sebastian_klose, version 8

Comments

MEwer Mar 18, 2010 at 3:32 PM 
In your command line example you spelled "Catalog" incorrectly.