Skip to content

EntityFramework 4.3 CodeFirst Trivial One File Example – Part 1

Updated: at 11:18 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: 

 
 

 

What To Do

We simply create a console version with Visual Studio 2010 in c#.  Using nuget package manager console we say “Install-Package EntityFramework”, then replace the primary Program.cs with the following file (you should add a connection string with the name SiteDB also if you want it to create a SqlServer Database.
 
Here is the code:
 
namespace ConApp
{
    internal class Program
    {
        private static void Main()
        {
            Database.SetInitializer<SiteDB>(new SiteDBInitialize());
            using (var myContext = new SiteDB())
            {
                var x = myContext.Presidents.ToList();
            }
        }
    }
<span class="kwrd">public</span> <span class="kwrd">class</span> SiteDB : DbContext
{
    <span class="kwrd">public</span> DbSet&lt;Presidents&gt; Presidents { get; set; }
}

<span class="kwrd">public</span> <span class="kwrd">class</span> Presidents
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    <span class="kwrd">public</span> <span class="kwrd">long</span> Id { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }
}

<span class="kwrd">public</span> <span class="kwrd">class</span> SiteDBInitialize :
    DropCreateDatabaseIfModelChanges&lt;SiteDB&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Seed(SiteDB context)
    {
        context.Presidents.Add(<span class="kwrd">new</span> Presidents { LastName = <span class="str">&quot;Reagan&quot;</span> });
        context.Presidents.Add(<span class="kwrd">new</span> Presidents { LastName = <span class="str">&quot;Bush&quot;</span> });
        context.Presidents.Add(<span class="kwrd">new</span> Presidents { LastName = <span class="str">&quot;Obama&quot;</span> });
        context.SaveChanges();
    }
}

}

I won’t go into details of all the steps because this is all very well documented on the EF site at this url among others:

http://msdn.microsoft.com/en-us/library/gg696189(v=vs.103).aspx

What is interesting to note is that I am implementing the interface DropCreateDatabaseIfModelChanges.  What stumped me for a while was that in my main console, we always call new SiteDBInitialize), however what that class implments determines the action on creation.  There are three choices.

  1. DropCreateDatabaseIfModelChanges
  2. DropCreateDatabaseAlways
  3. CreateDatabaseIfNotExists

The meaning is self explanatory, you just need to derive from the appropriate class depending on what your intention is.  All the calls can be seen here in the MSDN documentation:  http://msdn.microsoft.com/en-us/library/gg696142(v=vs.103).aspx

Hope this helps, read on to part 2 to find out how to add some columns and conditionally populate them.