How do I generate the migration to create the initial tables? - entity-framework-migrations

I want to be able to generate my table structure entirely using migrations.
Thus the first migration should create the tables.
I thought I could achieve this by dropping the database and deleting all the migrations as well as the Configuration.
However after I enable the migrations using
enable-migrations
and create my first migration using
Add-Migration One
the up method in the migration is empty.
In the configuration I have
AutomaticMigrationsEnabled = false;
In the Context Creation I have
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
If I run the application a blank database is created
I am using EF Code First 5 on Windows 7 with C# WInforms

I got it working using
Add-Migration InitialCreate
The initial time I tried this it didn't work. I arent sure why

Related

Entity Framework on a SQL instance

Every EF tutorial I've looked at requires LocalDB or SQL Express to be used in a code-first approach with EF.
Is there a way to connect to a traditional SQL DB (2014) instance using code-first EF and have EF create the schema in the DB? Or would I have to connect to a DB with an exsiting matching schema when switching to production?
It's fine to use LocalDB for dev purposes, but when deploying to production, I'd like to plug into an actual and existing SQL DB. Is there a way to do this without plugging into a DB that has had its schema manually made to match the EF models?
I would try using Entity Framework's Code First Migrations (http://msdn.microsoft.com/en-us/data/jj591621.aspx).
Short version:
1) In your DbContext, set the initializer to CreateDatabaseIfNotExists similar to Database.SetInitializer<YourDbContext>(new CreateDatabaseIfNotExists<YourDbContext>());
This will allow EF to create the DB if no database exists (the first time the application is run).
2) Next, go to the Package Manager Console, select your Database project (if separate), and enter the command Enable-Migrations. This will create some migration scaffolding and an initial migration.
Whenever you change your database model in code from then on, do the following steps:
3) After you've changed your code-first model, go to the Package Manager Console, select the Database project, and type the command Add-Migration MigrationNameHere This will scaffold out a new separate migration that can be applied to your database. Note, this command will run for whatever db is in your current connection string config.
4) To apply the migration, and update your database to the new schema, type the command Update-Database. If everything goes well, your database will be updated (with data) to the new schema! You should now be able to run your MVC project without db errors.
Keep in mind, this is the very basic version of db-migrations, please try it out on a dummy project first, and of course backup your data. If the changes are complex, or you need to do a special migration of data, you can edit the scaffolded migration code in the Migrations folder created, before doing the Update-Database.
Hope this helps!

Issue with entity framework migration. [Unable to generate an explicit migration because the following explicit migrations are pending]

I am using EF code first and asp.net MVC. Here is my technical stack.
Visual Studio 2010
Entity Framework 4.3.1
In my migrations folder, I can see three migrations files are existing.
InitialCreate
AddStandardException
DocumentScope
When I check my database I can see that _MigrationHistory table has all three migrations applied. Now I have added one more DbSet, and I want to write migrations for it. When I attempt to give this command
Add-Migration NewTable
It gives me this error :
Unable to generate an explicit migration because the following explicit migrations are pending: [201402121621095_AddStandardException, 201402190713571_DocumentScope]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
I don't understand why is it complaining about pending migrations whereas all migrations have been applied?
How do I even troubleshoot this ? I tried with -Debug switch but no luck.
I found a workaround to it. I have just commented code inside the Up() and Down() functions. Then ran Update-Database. It applied some dummy migrations and then reported that
Unable to update database to match the current model because there are
pending changes and automatic migration is disabled. Either write the
pending model changes to a code-based migration or enable automatic
migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to
true to enable automatic migration.
After this when i ran
Add-Migration NewTable
It gave me the correct result. Any idea whats going on here ?
You either need to run "update-database" from the package manager console to push your changes to the database OR you can delete the pending migration file ([201402121621095_AddStandardException]) from your Migrations folder and then re-run "add-migration" to create a brand new migration based off of your edits.
Explanation: "update-database" basically modifies existing table fields while "add-migration" works like git by making a snapshot of the distinct model changes. These snapshots show how the database evolved over time so they are more useful to your code user than the EF or the App itself.
That being said, it is possible that your newer classes have a quite different code signature which may not "flow" with the existing classes.
Solution: Modify or remove the previous migrations since the new migration will create a new data structure that won't use or need them

How do you downgrade a Entity Framework 5 migration in Visual Studio 2012?

I've noticed that when I create a code first database migration using add-migration it generates a Down() method as well as an Up() method.
How do I tell my database to downgrade?
After almost giving up with researching on Google I managed to find this quote from here:
http://msdn.microsoft.com/en-gb/data/jj591621.aspx#specific
Which Specifies:
Let’s say we want to migrate our database to the state it was in after running our AddBlogUrl migration. We can use the –TargetMigration switch to downgrade to this migration.
Run the Update-Database –TargetMigration: AddBlogUrl command in Package Manager Console.
This command will run the Down script for our AddBlogAbstract and AddPostClass migrations.
If you want to roll all the way back to an empty database then you can use the Update-Database –TargetMigration: $InitialDatabase command.
First get the name of the migration that was applied before the one you want to downgrade by issuing the Get-Migrations command.
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201508242303096_Bad_Migration
201508211842590_The_Migration_applied_before_it
201508211440252_And_another
This list shows the migrations listing the most recent applied migration first. Pick the migration that occurs in the list after the one you want to downgrade, ie the one applied before the one you want to downgrade.
Update-Database –TargetMigration: "<the migration applied before it>"
All migrations applied after the one specified will be down-graded in order starting with the latest migration applied first.

How can I reset the database migration of Entity Framework 4

I'm using ASP MVC 4 and EF 4.
I use the Package Manager Console to run Enable-Migration command.
I then did some changes and run Add-Migration after each of them.
I now want to clear all the small changes and re-create a single migration script.
How can I do that?
Where does EF remember the "last entity state" from which it derive the next Add-Migration script?
Thank you,
Ido.
I have found that the Enable-Migration script create the _MigrationHistory table which store the migration already apply to the database.
After I've delete the records in that table and the migration scripts from the Migration directory I've re-run Add-Migration and it create a single migration script.

Getting Initial Entity Framework Migrations Script

I just installed Entity Framework Migrations, added a property to a class, and gave EF Migrations a whirl.
My development database was promptly updated. So far, so good.
Now, I want to create a change script for this initial use of Migrations for the production database. Note there was a pre-existing database because I applied this to an existing project.
The migrations I have are:
PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201204102238194_AutomaticMigration
201203310233324_InitialCreate
PM>
I thought I could get a delta script using the following:
Update-Database -SourceMigration:201203310233324_InitialCreate -TargetMigration:201204102238194_AutomaticMigration -script
However, that gives me the error:
'201204102238194_AutomaticMigration' is not a valid migration.
Explicit migrations must be used for both source and target when
scripting the upgrade between them.
Just to see what would happen, I reversed the two parameters (backward migration) and did get the script I would expect after adding the -force flag (new columns dropped).
How can I get a script for this first migration?
The right way to start using EF migrations with an existing database is to start with adding an empty migration that contains the metadata of the current database.
I think that you have to roll back to a model that is compatible with the initial database schema. Then run the following command:
add-migration InitialSchema -IgnoreChanges
That should give you an initial migration, that does nothing, but contains the metadata of the current model. You can of course add migrations later with -IgnoreChanges if you've expanded your code model to cover more of the tables already present in the database.
Once you have that initial migration step in place, the scripting would work.
Generally I would not recommend to use automatic migrations unless you only ever intend to only use automatic migrations. If you want some kind of control over the changes to the database (including scripting them) then code-based migrations is the way.

Resources