The code first approach to using the Entity Framework can be extremely helpful in creating a new database while staying entirely within your C# code base. If you’re more comfortable with creating plain old class objects (POCO) and then having those translated into SQL driven structures, code first is for you. That said, the process by which updates to the code base are pushed to the database (migrations) can be a bit frustrating to use at times. Not all SQL Server features are supported in a code first approach. In addition, migrating your structures in Azure has its own set of problems.
If you want to roll back to a previous migration due to an error in the current migration or wanting to rewind and start over, the following command can be used from the Package Manager Console in Visual Studio. This will rewind and undo any migrations between the current and the “migration-name” migration.
update-database -TargetMigration "<migration-name>"
For example, if you have the following history of migrations in your project where the * indicates the current migration:
Use this command to roll back to the “AddColumn2” migration. Notice that the timestamp on the migration name is not included in the command.
update-database -TargetMigration "AddColumn2"
The migration history will then look like:
Notice that the migrations which were rolled back were not deleted. The next time you perform an update-database command, the migrations will be re-executed. You will need to delete the migration from your project entirely if you want to avoid this.