Debug code-first Entity Framework migration codes

code first migrations existing database
entity framework migrations publish
entity framework code first deploy to production
update-database specific migration
how do entity framework migrations work
azure devops entity framework migrations
update-database connection string
execute code first migrations (runs on application start)

I'm using Entity Framework code first in my website and I'm just wondering if there is any way to debug the migration codes. You know, like setting breakpoints and stuff like this.

I'm using Package Manager Console to update the database using Update-Database.

Thanks

I know that EF Code First Migrations is relatively new tool but don't forget about you are still in .NET.

So you can use:

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

After that you can see your InnerException.

Or you can use try...catch statement like this: Exception handling Entity Framework

Entity Framework - Code First Migration, I'm using Entity Framework code first in my website and I'm just wondering if there is any way to debug the migration codes. You know, like setting breakpoints  Easiest way to debug Seed-method in Code-first migrations in Entity Framework March 7, 2017 March 27, 2019 Antti K. Koskela Programming , Tech This post was most recently updated on March 27th, 2019.

To hit a break point in a db migration set the context to MigrateDatabaseToLatestVersion on initialise.

Database.SetInitializer(new MigrateDatabaseToLatestVersion<EnterContextHere, Configuration>());

Then you just debug as normal (run using f5) and the breakpoint will hit the first time you run the project.

The problem now is that if you debug a second time the migration will not run. This is because the __MigrationHistory table has been updated to say you have migrated to the latest version. To re-test the migration open the package manager console and downgrade to the previous migration:

Update-Database –TargetMigration: ThePreviousMigrationName

EF Migrations Command Reference, In the beginning, we might think it is not possible to debug our model configuration and seeding method in code first, since those codes cannot  Code First Migrations will compare the migrations in our Migrations folder with the ones that have been applied to the database. It will see that the AddBlogUrl migration needs to be applied, and run it. The MigrationsDemo.BlogContext database is now updated to include the Url column in the Blogs table.

My answer might be a bit silly but anyway here it goes. If you, like me, some times have problems in the Seed() method what I usually do is simply create a public method that calls the Protect Seed().

public void SeedDebug(AppDbContext context)
{
    Seed(context);
}

then in my HomeController I call this method in Debug mode.

public class HomeController : Controller
{
    var appDb = new AppDbContext();
    public ActionResult Index()
    {
        var config = new Configuration();
        config.SeedDebug(appDb);
        return View();
    }
}

I know it's a bit lame solution, but it's simple and quick. Of course this has to be done after the model been created. So step by step:

  1. comment the seed method and execute the update-database to create the model
  2. uncomment the method Seed() and plugin the "hack" I mentioned above.

  3. in the configuration disable Auto migrations

    AutomaticMigrationsEnabled = false;//if you have this disabled already skip this step

  4. Debug your application, fix the error and remove the "hack"

How do I code my first migration to an existing database? In this post we will walk through basics of Entity Framework migration commands and learn about Code First Approach. Entity Framework allows you to create database from plain classes. You can model your domain into classes and subsequently database can be created or updated from the model using Entity Framework.

You could add Console.WriteLine statements to the migration code (not a great solution)

Note, the messages are only shown if you run the migration code using the migrate.exe utility (in pacakges\EntityFramework.x.y.z\tools). They will not display if you run the migration through the Package Manager console.

Entity Framework Migrations are handled from the package manager console in Enable-Migrations: Enables Code First Migrations in a project. This cmdlet supports the common parameters: Verbose, Debug, ErrorAction,  In the beginning, we might think it is not possible to debug our model configuration and seeding method in code first, since those codes cannot be running by clicking the debug button in Visual Studio. Although the Package Manager Console command update-database DOES spit out some Exception info, it is difficult to dig into inner exceptions

Here's a more fail-proof method which will do the trick without much fuss:

Step#1: Place this piece of code right above the migration you want to debug:

public partial class ORACLE_Test : DbMigration
{
    public override void Up()
    {
        if (!System.Diagnostics.Debugger.IsAttached)
            System.Diagnostics.Debugger.Launch();

        AddColumn("TEST", "UR_USER_ID", x => x.Decimal(nullable: false, precision: 11, scale: 0, storeType: "number"));
        AddColumn("TEST", "UR_CLIENT_ID", x => x.Decimal(nullable: false, precision: 11, scale: 0, storeType: "number"));
        [...]
    }

    public override void Down()
    {
    }
}

Step#2: Compile the project containing your migrations

Step#3: Open a console inside the output directory (/bin/Debug, /bin/Release etc) containing the dll of your migrations

Step#4: Invoke migrate.exe with the /scriptFile parameter to launch the debugger and actually debug the desired db-migration

migrate.exe "Your.Migrations.Assembly.dll" /scriptFile="foo.sql" /verbose /startupConfigurationFile="Your.Migrations.Assembly.config"

Once the debugger-selector dialog pops up pick the visual studio instance that you have already opened.

Code First Migrations can be used to update a database from inside visual When you install Entity Framework using NuGet migrate.exe will be inside the This error occurs if running migrate when you haven't created a  Debug code-first Entity Framework migration codes (5) Here's a more fail-proof method which will do the trick without much fuss: Step#1: Place this piece of code right above the migration you want to debug:

Learn about the database migrations in EF 6: Automated and Code-based migration. Browse other questions tagged c# entity-framework ef-code-first entity-framework-6 ef-migrations or ask your own question. The Overflow Blog Podcast 236: A glitch in the Matrix

We'll also cover code first migrations in this article along with an understanding of how to Code First Approach using Entity Framework Core I've got the ability to do that coding and debugging on any one of the platforms. I'm using the Entity Framework in the Code First mode with automatic migrations enabled. Now, I have one entity whose table should not be managed (migrated) by the EF. Is there a way of disabling automatic migrations for one specific entity (i.e. table)?

NET Core in Action” and mine is “Entity Framework Core in Action”. the classes mapped to the database and the EF Core configuration – sometimes known as the Code-First Approach. Tips, · Watch out for error messages when you run the Add-Migration method. Hand-coding SQL migration scripts. I have a VS2012 MVC3 project that uses Entity Framework 5.0 Code First and deploys to staging and production servers using Web Deploy. It uses code first data migrations to synchronize the database

Comments
  • It's just standard C# code - so yes, of course, you can set breakpoints in it.....
  • but the application is not actually running since I'm using Package Manager Console.
  • Then do not upgrade from Package manager console but set the migration initializer as the default initializer so that the database is migated the first time your application connects to it.
  • I'm updating my database by using the migration code and I can't stop the app and run it again to run the initializer.
  • The reason I'm not using SQL is the code for the updating is rather complicated and it's almost impossible to implement it using SQL.
  • Yes, this works while running an Update-Database through the package manager console. Very handy!
  • I added this to the top of my Configuration.Seed method. It causes a popup that lets you select your Visual Studio to debug the code. However, my system hangs when I select it (perhaps unrelated).
  • Where to put this piece of code? if anyone can help out! Thanks.
  • In the constructor of your configuration class.
  • @Talon Go grab a coffee and by the time you're back probably another Visual Studio instance popped up. :)
  • Thanks Tom... It was the closest answer I could get. If no one answers this with a better solution I'm going to mark it as answer. :)
  • Or throw an Exception with your message that you want to return.
  • To which process are you attaching to?