This post details the setup process for Entity Framework code first migrations. Assume a new project with a User entity, with just 2 properties: Id and Name. The database schema is yet to be created.
Creating the Schema
- Install the Entity Framework package, through the Nuget package manager or other means - more information on the package can be found on the project site
- Add a UserConfiguration file to control the mapping between entity and schema
- Add IDataContext and DataContext files, here every persisted entity must be declared as a DbSet and the corresponding configuration file must be added to the model builder as shown
- Add a connection string in the web config file, to an existing database
- In the package manager console, select the project where the Entity Framework package has been installed. Type update-database and run. This will create the schema in the database given in the connection string
Updating the Schema
- Now, make a change to the User entity, by adding the property PhoneNumber then update the UserConfiguration file accordingly
- Going back to the package manager console (again checking to ensure the correct project is selected), type "add-migration AddedPhoneNumberToUser" and run
- A migration has been created
- Once again, in the package manager console, run update-database. The schema is now updated with the additional PhoneNumber property for the User table
Additional information
It is possible to configure entity framework to automatically create migrations when needed upon running update-database. In the Migrations folder of the project, create a Configuration file to allow automatic migrations.
Personally, I prefer to manually create migrations as it enables a greater level of awareness and control.
Conclusion
Using Entity Framework code first migrations decreases the amount of work required from the developer in creating database migrations. However, this is to the detriment of control over the finer details. For simple entities and simple migrations, Entity Framework migrations are perfectly sufficient. With more complex projects and schemas, the migrations an be troublesome to customise, but the specifics of which are beyond the scope of this blog post.
Comments
Post a Comment