EntityFramework Code First 4.3, Adding a Single Default Column to a Migration Enabled Project, Part 3

 

Introduction

This three part series demonstrates a very simple example of using Entity Framework Code First (Version 4.3) to create a SqlServer Table and populate it with data (that is part 1).  Part 2 adds two new columns to the table a populates the data conditionally (while migrating from a non migration enabled project), and Part 3 adds a new column with a default value to a migration enabled code first project.

As it happens, I watched President Obama drive by me in San Francisco yesterday so he will be the star of the post.  The table we will use is called Presidents, and the columns we will add are Year Elected and Current.  We will obviously only have one current president so we will have to have our migration conditionally set CurrentPresident to true for Obama.

 

 

 
 

Goal

In this post, we will show the steps necessary to add a single column (Party) to the Presidents table.  Because in Part 2 we enabled Code Migrations, this will be a lot simpler than in Part 2. 

 

Let’s Do it!

Now, we have a stable project that is running correctly with the database table Presidents defined as follows:

 

image

We want to add a new column “Party” so let’s update the model file (it’s in our original programs.cs file).  It will now be changed as follows:

public class Presidents
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string LastName { get; set; }

    // New Columns for first migration
    public int YearElected { get; set; }
    public bool CurrentPresident { get; set; }

    // New Column for second migration
    public string Party { get; set; }
}

We now have to create the .cs files in the MIgration folder that will know about this change.  So, we simply execute the command from the package manager Add-Migration AddNewColumnParty and we get the following results:

PM> Add-Migration AddNewColumnParty

Scaffolding migration ‘AddNewColumnParty’.

The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running ‘Add-Migration 201202171832107_AddNewColumnParty’ again.

Now, we want to add some customization because we know that Bush and Reagan are republicans and Obama is a democrat.  So, we add to the “Up()” method the following:

public override void Up()
{
    AddColumn("Presidents", "Party", c => c.String());

    Sql("UPDATE Presidents SET Party = 'Republican' WHERE LastName='ReaganX'");
    Sql("UPDATE Presidents SET Party = 'Republican' WHERE LastName='BushX'");
    Sql("UPDATE Presidents SET Party = 'Democrat' WHERE LastName='ObamaX'");
}

Now, we run the package manager command: Update-Database –Verbose and the work is done for us.

PM> Update-Database -Verbose

Using NuGet project ‘ConApp’.

Using StartUp project ‘ConApp’.

Target database is: ‘agelessemail’ (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration).

Applying explicit migrations: [201202171832107_AddNewColumnParty].

Applying explicit migration: 201202171832107_AddNewColumnParty.

ALTER TABLE [Presidents] ADD [Party] [nvarchar](max)

UPDATE Presidents SET Party = ‘Republican’ WHERE LastName=’ReaganX’

UPDATE Presidents SET Party = ‘Republican’ WHERE LastName=’BushX’

UPDATE Presidents SET Party = ‘Democrat’ WHERE LastName=’ObamaX’

[Inserting migration history record]

Now, looking at the generated data we have:

 

image

 

Keep in mind that “Update-Database” figured out what database we were on and just did the appropriate update.  The beauty of this is if some developer in the group is on a different version, all she has to do is say “Update-Database” and there database will be brought up to date along with whatever version was current at the time.

 

Conclusions

All I can say is “Congrats!” to the Microsoft engineers.  I’ve been doing ORM’s for a long time and have my doubts along the way about some Microsoft has rolled out, but this time, I think they really have listened and done what we need.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Mike Donner says:

    I like the article. I am trying to do a migration where I change the DatabaseGeneratedOption.None to DatabaseGeneratedOption.Identity with a starting seed of 25000. The reason it is None to start with is that I need to retain the Id from the old data but once it is converted to the new database I need it to start incrementing at 25000. Is this possible and if so, how do I go about doing it?

  2. Great article, short and precice. Helped med when I was learning Entity Framework.

Follow

Get every new post delivered to your Inbox

Join other followers: