Entity Framework Code First - Create new base - entity-framework

I've been working with EF a couple weeks now. I have about 25 migrations that I've created by using Add-Migration, I am synced up with all my environments (dev -> prod). I'd like to set this current state as a new baseline, is that possible? So this way I will have 1 initial migration to work with. I am not sure if EF tools has an easy way to do this, my other option was to delete all migration scripts in the folder, and delete all migration history in the table _MigrationHistory

You can do it like this.
Step 1 : Delete all the migration scripts on the Migrations folder.
Step 2 : Delete all the records on the __MigrationHistory table on the database.
Step 3 : PM> Add-Migration "My-First-Migration"
Step 4 : PM> Update-Database

You can do it like this.
Step 1 : Delete all the migration scripts on the Migrations folder.
Step 2 : Delete all the records on the __MigrationHistory table on the database.
Step 3 : Delete Database
Step 4 : PM> Add-Migration "$InitialDatabase"
now you update any thing in entity then not need to make new Migration
just update existing migration using below command.
Step 5 : PM> Update-Database -TargetMigration $InitialDatabase -Verbose
Step 6 : PM> Update-Database -Verbose

Related

How to Cleanup & generate fresh migration for existing DB?

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

EF Code First Drop Database?

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.

Entity Framework always has pending 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.

EF - Generate script from previous migration

I want to update database schema on production database. Usually in my development I just do Add-Migration and Update-Database.
My question is how to generate script so I can manually read through the query before executing in production environment? I've tried Update-Database -script but it gave me No pending explicit migrations.
Try running:
Update-Database -Script -SourceMigration: <initial-migration> -TargetMigration: <latest-migration>
Obviously replace <initial-migration> and <latest-migration> with the appropriate names of those migrations.
That should generate a script of all migrations at once.
More information can be found here on MSDN.

EF Code First Migration with Multiple Database / DbContext

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"