Ian Warburton
Ian Warburton

Reputation: 15726

Confused by Code First Migrations

Originally Code First meant that you create a model with code and then it generates a database for you.

With Migrations it now looks like I add/change the model and then I have to manually describe the changes using a new API.

Is this correct?

Upvotes: 1

Views: 272

Answers (2)

NSGaga
NSGaga

Reputation: 14312

Not actually correct - but there is certain overlapping of responsibilities that may be confusing.

A bit simplified - originally EF, code first was not made with incremental code / model changes in mind.

Migrations were introduced to address that - and is basically helping with a typical development life cycle, with your code and model evolving through different versions (and with staging, production in mind).

Migrations add __MigrationHistory table into your Db - and migrations are a 'tree way' synchronization process in between your database, code-model and that table (which saves and tracks the history).

However, it doesn't change the nature of the code-first - and all the changes are detected and scripted for you automatically (which is the whole point) - and also applied automatically (from the code, w/o PS) if you use the MigrateDatabaseToLatestVersion Db Initializer.

All you need to do is what's normally expected of you as a developer - to sort of put a 'checkpoint' on your code model - and create a migration - when you actually feel the time is right for that. You do that via PS console.

Then you can apply that migration via the console - or do it automatically from the code - on your development machine or any other deployed.

And here is a post of mine where I made a sort of hands on walkthrough for migrations - possible issues, and all put together in one place that I could think of.

Code first create tables

or this one...
MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"

Upvotes: 1

Alex S
Alex S

Reputation: 1221

I will try to "un-confuse" you :)

There are two separate components: EntityFramework and Migrations.

In Entity Framework you create model and database is generated for you. However, if you make changes to the model, you will need to manually update the database, otherwise EntityFramework will throw errors at you. This is where Code First Migration comes in. It manages the database upgrades for you, either manually or automatically.

Migration is optional but a nice package to avoid direct SQL interaction.

Please refer to http://msdn.microsoft.com/en-us/data/jj591621.aspx

Upvotes: 1

Related Questions