2016-01-21

How to Debug CodeFirst Migration Seed Method (C#, MVC)

If you are using Entity Framework code first migrations then you are familiar with the Seed method used to fill in initial data in your database structure. The Seed() method is executed every time you update-database within the Package Manager Console. There might be times that you would like to debug the Seed() method code. Setting breakpoint does not help, the debuger does not stop at the point set.
Remember that EF Code-First is just .NET code, so you can use:
if (System.Diagnostics.Debugger.IsAttached == false)
 System.Diagnostics.Debugger.Launch();
This makes the Seed() method to start a debugger instance once the execution comes to this point.

If you are not using Package Manager Console to update database to the latest version of migration, you could set db context to 'MigrateDatabaseToLatestVersion' on initialise.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EnterContextHere, Configuration>());
In this case you can use F5 to start and debug Seed method. Problem with this approach is that when you run the application for the second time the Seed() method will not be executed, as the database is already updated to latest version. In this case you can use following code to change migration version to version before the last one:
Update-Database –TargetMigration: ThePreviousMigrationName

No comments:

Post a Comment