EntityFramework 4.3 CodeFirst Trivial One File Example – Part 1

 

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

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();
            }
        }
    }

    public class SiteDB : DbContext
    {
        public DbSet<Presidents> Presidents { get; set; }
    }

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

    public class SiteDBInitialize :
        DropCreateDatabaseIfModelChanges<SiteDB>
    {
        protected override void Seed(SiteDB context)
        {
            context.Presidents.Add(new Presidents { LastName = "Reagan" });
            context.Presidents.Add(new Presidents { LastName = "Bush" });
            context.Presidents.Add(new Presidents { LastName = "Obama" });
            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.

 

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. 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:


Your Comments

*

Protected with IP Blacklist CloudIP Blacklist Cloud

Follow

Get every new post delivered to your Inbox

Join other followers: