Code-First Entity Framework with Migrations done right

I have been struggling to get a ASP.NET MVC 4 project with Entity Framework using Code First & Migrations and making the UserProfile class part of the migrations process. I Googled hi and low, but couldn’t get a great answer. Eventually through a lot of messing about I found a way that works.

Here are the steps:

  1. Create your MVC 4 project.
  2. Add a Data project
  3. Install EntityFramework in Data project
  4. Reference System.Data.Entity from Data project
  5. Reference Data project from Web project
  6. Add Models and Context to Data project as per Code First instructions
  7. Add a temp controller using the context and a model from the Data project
  8. Run the app
  9. Create a record using the temp controller above. Success will indicate EF is doing its thing
  10. Deploy to Azure.
  11. Repeat steps 8 and 9 on Azure.
  12. Enable Migrations on the Data project. If the migrations folder etc gets created in the Web project you’re on the wrong track.
  13. Move UserProfile class in AccountModel in Web project to your Models in the Data project.
  14. Remove the UserContext context class & try and build.
  15. This will throw a lot of errors. Update the references to refer to your context (as defined in the Data project) and to your UserProfile class (that you’ve just moved).
  16. Add more fields to the UserProfile class like Fullname.
  17. Run Add-Migration.
  18. This will create a bad migration so you will manually have to override this. The migration will initially recraeate the whle table. Overwrite this to only add the new column(s). Don’t forget to delete the new columns in the Drop part
  19. Run Update-Database
  20. Deploy to Azure again (with migrations) to see your data structure the way you want.
  21. Now you can use the power of Entity Framework migrations from a separate project (good), with the User Profile included (better) and in Azure (awesomeness!)

Lemme know if I could’ve done something better.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: