Wednesday, September 16, 2015

Debugging your Seed method when running Entity Framework's Update-Database Powershell command

Sometimes when running the Update-Database Powershell command when using Entity Framework's Code First development model, you can have an exception generated within your Seed method. Sadly, this is only communicated to you via the Powershell window:


By default, as the Seed method is not being executed within a context which has a debugger attached, there is no way to interact with the exception as it occurs or set a break point within the Seed method to step through the code as it executes.

Wouldn't it be nice if you could take advantage of Visual Studio's debugger and interact with the code within the Seed method to get to the bottom of that pesky exception? Thankfully this is possible with a little bit of custom code that instantiates a new debugger if one is not already attached. Using code to instantiate a new debugger?! Surely this is not possible I hear you asking... I did not know this was possible either until I hit this problem and this piece of code made me smile, ALOT!

if (System.Diagnostics.Debugger.IsAttached == false)
  System.Diagnostics.Debugger.Launch();

That is all there is to it. This code will determine if a debugger is already attached to your execution context. If not, a dialog is displayed allowing you to select what debugger you would like to attach:


As you can see from the capture above, you have the option of opening a new instance of Visual Studio to debug in or not opening a debugger at all. Note, you can also specify the version of Visual Studio you want to use. How cool is that? Hold on, it gets better.

If you select to debug in a new instance of Visual Studio 2013, Configuration.cs will open in a new window and display the warmly welcomed user-unhanded exception dialog as it occurs within the Seed method:


From here you have all the familiar functionality to drill into the exception details to determine what went wrong. Nice. There is still more though.

You can even set a break point in the debug instance of Visual Studio within the Seed method and step through the code as it executes:



Now that is seriously cool.

I generally add this piece of code to the top of my Seed method so the magic can happen whenever I execute the Update-Database Powershell command. However, if you are updating your data model frequently, you may only want to include this code when you have a problem with the Seed method (or any other code being executed as part of the Update-Database process).

You can find a project here which illustrates this in action. All you will need to do is open it in Visual Studio 2013, build it to restore the packages (ensure you have NuGet version 2.7+ installed - see here for why) and run Update-Database from the Package Manager Console.