Skip to content

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

Updated: at 02:12 PM

 

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.

 

 

image_thumb4_thumb2
I need practice with my cell phone camera (obviously) 

Part 1 Building a 1 File Console App That Creates a SqlServer Table and Populates it With Data
Part 2 Adding Two New Columns To the Customer Table and Populating Data Conditionally using New Migrations Feature (With Upgrade To Code Migrations from Project Without Code Migrations)
Part 3 Changing your CodeFirst DataModel with Migrations Enabled
 
For those wanting the real code, the final visual studio solution after part 3, includes parts 1 and 2 information is here: 

 
 

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; }
<span class="rem">// New Columns for first migration</span>
<span class="kwrd">public</span> <span class="kwrd">int</span> YearElected { get; set; }
<span class="kwrd">public</span> <span class="kwrd">bool</span> CurrentPresident { get; set; }

<span class="rem">// New Column for second migration</span>
<span class="kwrd">public</span> <span class="kwrd">string</span> 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(<span class="str">&quot;UPDATE Presidents SET Party = 'Republican' WHERE LastName='ReaganX'&quot;</span>);
Sql(<span class="str">&quot;UPDATE Presidents SET Party = 'Republican' WHERE LastName='BushX'&quot;</span>);
Sql(<span class="str">&quot;UPDATE Presidents SET Party = 'Democrat' WHERE LastName='ObamaX'&quot;</span>);

}

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.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects