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.

4 comments:

  1. Thank you for giving the information and it is use full for me. training with placement company in Hyderabad

    ReplyDelete
  2. Today Telugu news updates provide us the information of breaking news and live updates. we get live news, political, education, technology, etc. Today Telugu news gives the best news updates. It also keeps its readers informed about the latest happenings in the world with instant updates.

    ReplyDelete
  3. Thanks for sharing such a valuable information...
    AngularJS Training in Bangalore | AngularJS Course Fees | AngularJS 6 - i Digital Academy - AngularJS Training in Bangalore - Learn AngularJS 6 from Expert Real-time Trainers
    at i Digital Academy with Live Projects and Placement Assistance. Book a Free Demo Today.

    ReplyDelete