...

/

Handling Mistakes and Avoiding Pitfalls

Handling Mistakes and Avoiding Pitfalls

Learn how to handle mistakes and avoid pitfalls when working with the Code-First workflow.

Overview

It is common to run into some challenges while working with migrations and making changes to the data models. In this lesson, we’ll review tips for avoiding common mistakes when working with EF Core.

Removing a migration

At some point, you may discover that a previously added migration is not needed. We can remove any migration not applied to the database using the code sample below:

Press + to interact
dotnet ef migrations remove

This command removes the migration and reverts the model to a previous snapshot.

Note: It is good practice to avoid removing migrations applied to production databases. If a migration is removed, we can’t revert those migrations from the databases, which might break the assumptions made by subsequent migrations.

Reverting a migration

What happens to a migration applied to a database? Can it be removed? Yes, we can remove migrations by reverting to a previous migration. Let’s go through how to do this with the project below:

{
    "version": "0.2.0",
    "configurations": [
        {
            // Use IntelliSense to find out which attributes exist for C# debugging
            // Use hover for the description of the existing attributes
            // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceFolder}/bin/Debug/net6.0/CodeFirst.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
            "console": "internalConsole",
            "stopAtEntry": false
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}
Project for reverting migrations

In this project, ...