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:
- Create your MVC 4 project.
- Add a Data project
- Install EntityFramework in Data project
- Reference System.Data.Entity from Data project
- Reference Data project from Web project
- Add Models and Context to Data project as per Code First instructions
- Add a temp controller using the context and a model from the Data project
- Run the app
- Create a record using the temp controller above. Success will indicate EF is doing its thing
- Deploy to Azure.
- Repeat steps 8 and 9 on Azure.
- Enable Migrations on the Data project. If the migrations folder etc gets created in the Web project you’re on the wrong track.
- Move UserProfile class in AccountModel in Web project to your Models in the Data project.
- Remove the UserContext context class & try and build.
- 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).
- Add more fields to the UserProfile class like Fullname.
- Run Add-Migration.
- 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
- Run Update-Database
- Deploy to Azure again (with migrations) to see your data structure the way you want.
- 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.