Tuesday, 26 November 2013

Quick How To: Entity Framework Auto Migrations

The requirement in the project is to store some tracking information in a SQL database. I have created a POCO out of basic value types to house the data. I want each instance of this object to be persisted as a row in a table: enter EF 6.0. Its as simple as ever to bring in the EF nuget package at the Package Manager console:

Install-Package EntityFramework -ProjectName <ProjectName>

Now we have the tools to set up a database context for the POCO. The database context will give us the ability to store, update, query and delete collections of objects - we just have the one for this example, so our data container, db context and tracking class all together look like this:

Then, again from the console enable migrations:

Enable-Migrations -ProjectName <ProjectName>

In the project you added EF to, find the .\Migrations\Configuration.cs class. Set AutomaticMigrationsEnabled to true in the constructor:

public Configuration()
    AutomaticMigrationsEnabled = true;

Now we're all set to have EF automatically put our database together. It will create tables, stored procedures, primary and foreign keys based on the signature of our objects. Lastly, run this command from the Package Manager console:

Update-Database -Verbose -ProjectName "<Project.Name>" -ConnectionProviderName "System.Data.SqlClient" -ConnectionString "xxx"

This is same command that can be run when new entities are added to the context, or when new properties are added to an existing entity. Note that this command won't support the removal of a property by default as it will result in data loss. Column renames are supported, but beyond the scope of this blog. Watch this video tutorial for further instruction. And here for more examples of maintenance commands.

No comments:

Post a Comment