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.
What To Do
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<Presidents> 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<SiteDB> { <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">"Reagan"</span> }); context.Presidents.Add(<span class="kwrd">new</span> Presidents { LastName = <span class="str">"Bush"</span> }); context.Presidents.Add(<span class="kwrd">new</span> Presidents { LastName = <span class="str">"Obama"</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.
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.