I'm trying to figure out the syntax to bring migrations down to an empty database as in call the down method on the inital create migration. Does anyone know the proper syntax to call the Down method in a migration something akin to this:
Update-Database -StartupProjectName "Infrastructure.Data" -TargetMigration 0
update-database -startupproject someproject -targetmigration 0
That will bring you back to a completely empty database.
I assembled a complete reference to the package manager commands for ef migrations.
Related
We wish to get rid of 100s of migration classes as DB schema in production is final.
Here are the steps I followed:
Delete Migrations folder.
Add-Migration -??
What command line switches, could help us?
EDIT:
If all goes well Up() method of migration should be empty right? For
example following is wrong generation on Add-Migration. Because if we
execute the project we will get duplicate table errors.
public partial class Sanity : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AccountPreferences",
c => new
{
AccountID = c.Guid(nullable: false),
}
.... for 1000s of tables
}
}
A clean migration would be something: when trying Add-Migration on subsequent changes, should not be getting any error.
Unable to generate an explicit migration because the following
explicit migrations are pending: [201712281054591_Sanity]. Apply the
pending explicit migrations before attempting to generate a new
explicit migration.
As you can see if we happen to execute Update-Database will get table already exist error.
Are we forced to always retains all migration copies?
See if this can help:
MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"
Entity framework code first - how to run Update-Database for production database
How to delete and recreate from scratch an existing EF Code First database
note:
I'm writing this from memory, if you have issues let me know and I'll recheck exactly.
Also, my knowledge on this is from slightly older versions of EF as I haven't done much work there recently, but I doubt much has changed.
From what I can tell, if you want to...
a) keep the db,
b) clean your project migrations,
c) have the 2 'match', be in sync:
do the following:
- Remove the migration folder (your project)
- Run Add-Migration Initial - then should add one migration
- caution: it is safe but do backup, change connection string etc. before the next step
- Run Update-Database -Script - that doesn't update the db but creates the SQL script, including the migration table
- find the INSERT INTO [__MigrationHistory] records, just run those (on your db), insert them into the database
...then test with Add-Migration again, to see if it is going to make anything, should yield no new migrations, empty one.
Please read through the first link above and adjust approach as needed.
I'm sure there might be easier, shorter ways to do this (via PM console) but unaware of it at the moment.
Open your database.
Clear table __MigrationHistory
Remove migrations in the folder
Run Add-Migration MigrationName
Almost the same as accepted one, but no scripting the initial migration.
Drop the __MigrationHistory db table
Remove all the migration files in the Migrations folder
Run Add-migration Initial in Package Manager Console
Comment out the code inside of the Up method in the Initial Migration
Run Update-database in PM Console (just to create a Migration Entry)
Remove comments in the Initial migration
Wonder how long it will be "final" ?
Use:
Add-Migration Initial
After removing the migrations folders
I want to use EF code first migrations to create my models in the database. However, the database I will use already exists and is shared by other applications. My question is:
Do migrations erase the database? That would be a disaster!
Do migrations erase anything at all?
Q : Do migrations erase the database ?
A : No.You can do that without erasing it.
You have to do it as shown below on the Package Manger console.
Step 1 :
PM > Add-Migration InitialCreate –IgnoreChanges
Above command will create an empty migration with the current model as a snapshot.
Step 2 :
PM > Update-Database
Above command will apply the InitialCreate migration to the database. Hence the actual migration doesn’t contain any changes, it will add a row to the __MigrationsHistory table indicating that this migration has already been applied.
You can read more about it here : CF Migrations with an existing database
What I usually do in this situation is create a migration to the existing database and then remove everything out of the Up and Down methods and run the update. This way your code first migrations will be up to date with whats currently in the database so any new schema changes that are made will be the only thing picked up by adding a second migration.
Using Entity Framework 6, with a SQL Server database and code first migrations, I have migrations set up and running "happily", however I'm finding that every time I go to add another migration I get the following error first off:
Unable to generate an explicit migration because the following explicit migrations are pending: [201602090629398_Initial, 201602090638322_FixSitePageColumns, 201602110313468_RemoveRequiredTemplateId]. Apply the pending explicit migrations before attempting to generate a new explicit migration."
If I run update-database -force it complains (naturally) that the script fails because of already having been applied. A strange combination of doign this again and then the add-migration works and I can carry on updating to the latest migration.
The list of "pending" migrations also grows with every addded migration over time.
What could cause this "pending" state, when the migration HAS already been applied? I can confirm that the database has already been updated, the migration exists in __MigrationHistory, and the program is running along happily.
EDIT
I've also just run get-migrations and the following is being returned:
PM> get-migrations
Retrieving migrations that have been applied to the target database.
201602110313468_RemoveRequiredTemplateId
201602110311536_RemoveRequiredTemplateId
201602090638322_FixSitePageColumns
201602090629398_Initial
The weird thing here (possibly a red herring) is that 201602110311536_RemoveRequiredTemplateId is not a migration in my project, I think it may have been one that I created and then deleted, I didn't ever implicitly apply it to the database but it's in the __MigrationHistory table.
This happened to me because when running Add-Migration it couldn't connect to the database to see what migrations had been applied. I don't have my password stored in the connection string. The fix was to run Add-Migration specifying a complete -ConnectionString and -SqlProvider
Add-Migration MigrationName -verbose -ConnectionString "data source=foo.database.windows.net;initial catalog=FOO_DB;user id=admin;password=`"REDACTED`";MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient"
Remove the entry for removerequiredtemplateid from the migrations database table and rerun your migration procedure.
Optionally, delete the table altogether, delete all of your migrations, rerun enable-migrations, create a new initial migration and run update-database again (basically, create a fresh start).
Remember to make the required backups beforehand.
I am very, very new to using migrations, but based on the answer to the SO question Database is not getting created at first time, using the Powershell command Update-Database -Script should give me a script to execute outside of automatic migrations. Yet when I try running that command, I get an error message that says:
Unable to update database to match the current model because there are
pending changes and automatic migration is disabled
I would rather follow Chris Pratt's sage advice - in his answer to the linked question - and leave automatic migrations disabled, but the alternative he offers is insisting on automatic migrations.
I am trying to create the database from scratch, using the CreateDatabaseIfNotExists initializer.
It means there are changes to your current model that haven't been added to a migration.
Try:
Add-Migration YourMigrationName
Update-Database -Script
This will first create a migration with the updated model changes, then you can generate the update database SQL script.
I have two database each with their own dbcontext. I've setup two migration configurations. I can add a migration for the first db ust fine (Add-Migration DB1_InitialCreate -ConfigurationTypeName DB1Configuration). When I try to create an initial migration with the second db using: Add-Migration DB2_InitialCreate -ConfigurationTypeName DB2Configuration, I get the following error:
Unable to generate an explicit migration because the following explicit migrations are pending: [201205082215265_DB1_InitialCreate]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
So I do what it says and update the database with:
Update-Database -ConfigurationTypeName DB1Configuration
Then I try to add a migration again for the second db but I keep getting the same error.
Any ideas on how to get migrations working for two databases/contexts?
I've been able to answer my own question. My two configuration classes existed in the same namespace. As soon as I separated them, everything worked.
With Entity Framework 6 it's easy.
It's the same procedure for both multiple DbContexts for one database and for multiple DbContexts for each their own database:
Enable-Migrations -ContextTypeName <DbContext-Name-with-Namespaces> -MigrationsDirectory:<Migrations-Directory-Name>
Add-Migration -configuration <DbContext-Migrations-Configuration-Class-with-Namespaces> <Migrations-Name>
Update-Database -configuration <DbContext-Migrations-Configuration-Class-with-Namespaces> -Verbose
Source
It's been a while, but this could be a better answer to your problem :)
Update-Database -ConfigurationTypeName "SlaveConfiguration"
-StartupProjectName "FacturatieMVCv2.Data" -Verbose
-ConnectionString "connstring;"
-ConnectionProviderName "System.Data.SqlClient"