Code first migrations - how to rollback first migration - ef-code-first

Using code first migrations it is trivial to migrate to any given migration by using -TargetMigration [MigrationName].
But how do you rollback to before the first migration? What migration do you target for that? The first migration has a Down() just like the rest and the logic is sound - but how do I get it to execute via a update-database command?

Use this command:
Update-Database -Target 0

Related

How to output SQLite database in a different project in EF Core 3

I have a solution with 2 projects
src
|-ProjectA
|-ProjectB
ProjectA is a class library targeting netstandard2.1, it contains the DbContext (with "Data Source=blog.db"), the entities and it has a dependency on Microsoft.EntityFrameworkCore.Sqlite
ProjectB targets a netcoreapp3.1 and has a dependency on Microsoft.EntityFrameworkCore.Design. I just use it to manage migrations because migrations need a framework.
The SQLite database does not exist, so I create the first migration with dotnet tools from the ProjectB
dotnet ef migrations add InitialCreate --project ../ProjectA
and it successfully creates the Migrations folder with the initial one.
Now I want to update the db so that the SQLite *.db is actually created.
If I do this:
dotnet ef database update --project ../ProjectA
the *.db file is created but in the ProjectB. I want the file to be output in the ProjectA but I cannot find a way to do so.
The doc does not seem to mention anything and neither the ef database update --help
UPDATE 1: I have tried to create and update migrations from the ProjectA instead and point to the executable project like this:
dotnet ef migrations add InitialCreate --startup-project ../ProjectB
and it creates properly the Migrations in ProjectA. Now I try to apply them to generate the *.db like this:
dotnet ef database update --startup-project ../ProjectB
and it generates the *.db file... but again in ProjectB! not in ProjectA where I want.
It seems wherever the Microsoft.EntityFrameworkCore.Design package is, the generated database is placed there.
UPDATE 2: Specifying the project when updating database to point to where the DbContext is, didn't work either. It keeps generating the *.db in Project B
dotnet ef database update --startup-project ../Sasw.SimpleBlog.Storage.SQLite.Migrator/ --project ./
I fixed it by specifying a full path at my connection string. It's sufficient because this path should be configurable in settings.
public class DatabaseContext
: DbContext
{
public DbSet<Thing> Things{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlite("Data Source=D:\\database.db");
}
}
The only problem left here is how to pass this connection string at runtime by using the dotnet ef CLI. But that seems an open question atm https://github.com/aspnet/EntityFrameworkCore/issues/10750
I know its kinda late for this response but maybe this helps, i haven't tried it.
Have you tried choosing a different default project in Visual Studio's Package Manager Console?

A parameter cannot be found that matches parameter name 'Script' [duplicate]

I'm building a MVC application with .Net Core and I need to generate the script of a migration.
With EF6 I did run the command
update-database -script
but when I try to do the same with .net Core is throwing the next exception:
Update-Database : A parameter cannot be found that matches parameter
name 'script'
Do you know if there is an equivalent for EF Core?
As per EF documentation you can use :
Script-Migration
If you want to just script all the migrations you can simply call it from Package Manager console like that. If you want to just script the changes from the last migration you can call it like this:
Script-Migration -From <PreviousMigration> -To <LastMigration>
Be sure to check the docs, there're a few more options to the command.
dotnet ef migrations script --help
Usage: dotnet ef migrations script [arguments] [options]
Arguments:
<FROM> The starting migration. Defaults to '0' (the initial database).
<TO> The ending migration. Defaults to the last migration.
Options:
-o|--output <FILE> The file to write the result to.
-i|--idempotent Generate a script that can be used on a database at any migration.
-c|--context <DBCONTEXT> The DbContext to use.
-p|--project <PROJECT> The project to use.
-s|--startup-project <PROJECT> The startup project to use.
--framework <FRAMEWORK> The target framework.
--configuration <CONFIGURATION> The configuration to use.
--runtime <RUNTIME_IDENTIFIER> The runtime to use.
--msbuildprojectextensionspath <PATH> The MSBuild project extensions path. Defaults to "obj".
--no-build Don't build the project. Only use this when the build is up-to-date.
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
so,you can try
dotnet ef migrations script ver1 ver2
dotnet ef migrations script ver1 ver2 -o ./script.sql
This works in .Net Core 2.1
You can use dotnet core cli to generate script
dotnet ef migrations script
Also you can put this to file with new power shell out-file command.
dotnet ef migrations script | out-file ./script.sql
You can also generate a script to rollback a migration by reversing the parameters to Script-Migration. For example, if you have two migrations, BadLatestMigration and GoodPreviousMigration, you can revert to GoodPreviousMigration by using the following command
Script-Migration BadLatestMigration GoodPreviousMigration
Afterwards be sure to Remove-Migration to remove the bad migration
Remove-Migration
This works in .Net Core 2.2.0
This also generates only the SQL
Update-Database -script -TargetMigration TO -SourceMigration FROM

How to change the output folder for migrations with asp.net Core?

Does anyone know how to change the output directory of the following command?
dotnet ef migrations add Initial --context EsportshubApi.Models.ApplicationDbContext
I tried to add the option:
--content-root-path 'Migrations/Identity'
But that doesn't do anything. There is a --data-dir option as well and something else with directory. But none of them is the output for migrations.
My problem is that I have 2 DbContexts so I want their migrations to be separated.
dotnet ef migrations add Initial --context EsportshubApi.Models.ApplicationDbContext -o YourFolderPath
dotnet ef migrations add
Adds a new migration.
Arguments:
Argument
Description
<NAME>
The name of the migration.
Options:
Option
Short
Description
--output-dir <PATH>
-o
The directory used to output the files. Paths are relative to the target project directory. Defaults to "Migrations".
--namespace <NAMESPACE>
-n
The namespace to use for the generated classes. Defaults to generated from the output directory. Added in EF Core 5.0.
Also here are the common options you can use with this command.
Source
For Package Manager Console run this command:
PM> Add-Migration 001 -OutputDir "Data/Migrations"
My structure is:
.AspCoreProject
-Data
-Migrations
20190721162938_001.cs
MainDbContextModelSnapshot.cs
Update:
For removing last migration use:
PM> Remove-Migration
Note: If the migration is already applied to the database, then you will get this error:
The migration '20190721162938_001' has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.
Then run:
PM> Remove-Migration -Force
If your migration is not the last migration. first, rollback to the migration you need by Update-Database then delete all migration classes after that migration.
PM> Update-Database -Migration 001
This will revert all migrations after 001
In EF Core 5.0, you are free to move Migration files and changes their namespace manually. New migrations are created as siblings of the last migration. Alternatively, you can specify the directory at generation time as follows:
.Net core CLI
dotnet ef migrations add InitialCreate --output-dir Your/Directory
Package Manager Console
Add-Migration InitialCreate -OutputDir Your\Directory
EF Core 5.0 documentation
You just need to use -o Or --output option with your command,
To do so, you need to explore to your root project folder, eg: C:\project\SampleAPi\
and use this command
dotnet ef migrations add DbInitial --context SampleAPi.Infrastructure.DbContext -o Infrastructure/Migrations
and then
dotnet ef database update

Mark an individual Doctrine migration as ran/executed

Is there a way that I can mark a Doctrine migration as "ran" or "executed" in the way that it won't be shown as a migration that needs to be migrated?
app/console doctrine:migrations:migrate --add Version20140409203042
I don't see anything in the --help.
The reason for doing this is my DB is up to date and imported from elsewhere, but this migration is asking to be ran every time I run a doctrine:migrations:migrate.
I found that this functionality falls under the version command:
Use this command to add a single version:
Symfony 2/3
app/console doctrine:migrations:version 20140430223207 --add
Symfony 4
bin/console --env=staging doctrine:migrations:version 'Application\Migrations\Version20220803073040' --add
Use this command to add them all:
app/console doctrine:migrations:version --add --all
In your database is table where stored doctrine migrations. You can just add line with version id (20140409203042). Default name of this table is migration_versions, i think, or you can find name in config (http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html)
It is one possible solutions for doing migrations wihout running it. But you really should control all queries, if it ok. If one, or more are missing, you should do migrations with queries commented out.
In newer versions of doctrine the migration version name contains a namespace (Skipping Migrations)
Now the command may look like this:
bin/console doctrine:migrations:version 'DoctrineMigrations\Version20220407777666' --add

update-database command fails in code first migrations

I am trying to follow the tutorial http://www.asp.net/web-forms/tutorials/data-access/model-binding/retrieving-data.
When I am trying the update-database command in PM console, i get the following error.
Cannot attach the file 'D:\ASPdotNet\ContosoUniversity\ContosoUniversity\App_Data\ContosoUniversity.Models.SchoolContext.mdf' as database 'ContosoUniversity.Models.SchoolContext'.
Just ran into the exact same issue. To resolve I used,
Open the "Developer Command Propmpt for VisualStudio" under your start/programs menu and
run the following commands:
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
Rebuild the solution and try to update the database again.

Resources