Dotneteers.net
All for .net, .net for all!

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application

In this new series of posts about Entity Framework I’d like to help those software developers who intend to use Entity Framework Code First in their projects ­­— either coding for business or fun. I assume no special prerequisites, but a basic experience with Visual Studio and the C# programming language.

A good chef uses only quality ingredients. In this series you’re going to use only ingredients that provide delicious result, by means of simple, clear-cut and working sample applications.

A great cooking book contains not only recipes, but also teaches you a few technique. So do the posts in this series. Beside concrete recipes you’ll learn several basic techniques. Unlike traditional gastronomy books, this one intends to explain you what’s going on during the cooking process during the background — in other words, you’ll learn about how things work in Entity Framework.

Obtaining Quality Ingredients

Before starting to deal with the first recipe, let’s set up our kitchen equipment. To work with Entity Framework Code First, you need the following tools:

  • Visual Studio 2010 with Service Pack 1 — You can also use Visual C# Express 2010, however, if you can afford it, use Visual Studio 2010 Professional edition (or higher). The instructions and figures in this series assume you’re using Visual Studio 2010 Professional.
  • NuGet — This ingredient is a great package manager for Visual Studio, and you’ll use it to add prefabricated components to your projects.
  • Entity Framework — This package is the key ingredient you’re going to use in all recipes. You’ll add this component to your projects using NuGet.

To prepare the ingredients, follow these steps:

  1. Start Visual Studio 2010.
  2. With the Tools >> Extension Manager command, open the Extension Manager dialog, and click the Online Gallery tab, as it is shown in Figure 1.

    f001

    Figure 1: The Extension Manager dialog

  3. Type NuGet into the search box to filter extensions. Select the NuGet Package Manager item in the list, as shown in Figure 2, and click Download.

    f002

    Figure 2: Selecting the NuGet extension

  4. The Extension Manager downloads NuGet and launches the Visual Studio Extension Installer, as shown in Figure 3. Click Install to go on with NuGet setup. In a few seconds NuGet is installed. Click the Close button to exit the setup utility.

    f003

    Figure 3: The Visual Studio Extension Installer utility

  5. In order to complete the installation of NuGet, click Restart Now at the bottom of Extension Manager.
  6. When Visual Studio is restarted, you can check in Extension Manager that NuGet is installed, as shown in Figure 4.

    f004

    Figure 4: NuGet is now installed in Visual Studio

Entity Framework is a package managed by NuGet. You need a project Entity Framework components can be added to, so let’s create it.

Recipe #1: Creating a Single-Table Application with Code First

This recipe is your entry to learn Code First. You will create an application that manages a single table or order records.

Ingredients

  • A class describing an entity (Order)
  • A class describing a data context (OrderDatabaseContext)
  • A few lines of simple code to store a single entity into the database

How to Cook

To cook this recipe, follow these steps:

  1. Use the File >> New >> Project command and select the Console Application template under Visual C#. Set the name of the project to Recipe01. Click OK.
  2. Add a new class file to the project, name it Order.cs. Type or copy the following code into this new file:

    1. using System;
    2.  
    3. namespace Recipe01
    4. {
    5.     public class Order
    6.     {
    7.         public int Id { get; set; }
    8.         public string Customer { get; set; }
    9.         public DateTime OrderDate { get; set; }
    10.         public decimal Total { get; set; }
    11.         public string Status { get; set; }
    12.     }
    13. }

    The Order class represents a table in the database managing purchase orders. Each Order instance will be one data row in the data table, when saved to the database.

  3. To turn the Order class into more powerful than its declaration tells, it’s time to add the power of Entity Framework Code First to the project. Right-click the References node under the Recipe01 project and select the Manage NuGet Packages command from the context menu.
  4. The Manage NuGet Packages dialog appears. It looks very similar as Extension Manager. Select the Online tab, and type Entity in the search box. In a few seconds the list is populated with packages matching the Entity search term. Select EntityFramework from the list, as shown in Figure 5, and click Install.

    f005

    Figure 5: Selecting the EntityFramework package

  5. Accept the licence terms when asked. In a few seconds the EntityFramework package is installed and added to your project. Click Close to exit the NuGet Package Manager. The EntityFramework assembly is now a part of your project in pair with the packages.config file – this file contains information about packages added with NuGet to your project – as shown in Figure 6.

    f006

    Figure 6: The EntityFramework assembly and the packages.config file

  6. Add a new class file to the project, name it OrderDatabaseContext.cs. Copy the following code into this new file:

    1. using System.Data.Entity;
    2.  
    3. namespace Recipe01
    4. {
    5.     public class OrderDatabaseContext : DbContext
    6.     {
    7.         public DbSet<Order> Orders { get; set; }
    8.     }
    9. }

    The OrderDatabaseContext class can be used to access to your database entities. The declaration of Orders property (due to the DbSet<Order> type) allows you using this context to access and modify Order entities.

  7. Believe or not, the core of your simple application is completed. You need to create a few code lines to try how it works. Open the Program.cs file, and change the Main method’s body to the code indicated in the following listing:

    1. using System;
    2. using System.Linq;
    3.  
    4. namespace Recipe01
    5. {
    6.     class Program
    7.     {
    8.         static void Main(string[] args)
    9.         {
    10.             using (var context = new OrderDatabaseContext())
    11.             {
    12.                 var newOrder = new Order
    13.                                    {
    14.                                        Customer = "IntelliGrail Co.",
    15.                                        OrderDate = DateTime.Now,
    16.                                        Status = "NEW",
    17.                                        Total = 100
    18.                                    };
    19.                 context.Orders.Add(newOrder);
    20.                 context.SaveChanges();
    21.             }
    22.  
    23.             using (var context = new OrderDatabaseContext())
    24.             {
    25.                 var order = context.Orders.FirstOrDefault();
    26.                 Console.WriteLine("{0}: {1}, {2}, {3}",
    27.                     order.Customer, order.OrderDate, order.Status,
    28.                     order.Total);
    29.             }
    30.         }
    31.     }
    32. }

Taste It

Now your first recipe is ready to taste. To check what’s out of oven, follow these steps:

  1. Use Ctrl+F5 (Debug >> Start Without Debugging) to run the application. After you start it, it seems for a few seconds that it does not do anything, and then the result appears on the screen as shown in Figure 7. The simple code in Program.cs inserts a new data record into a database and then reads it from there and displays it.

    f007

    Figure 7: The result of Recipe01

  2. Use the Server Explorer window (View >> Server Explorer) to create a new Data connection (right-click the Data Connections node and select Add Connection). If you have never done it before, select Microsoft SQL Server in the Choose Data Source dialog, as shown in Figure 8, and click Continue.

    f008

    Figure 8: Selecting Microsoft SQL Server as Data Source

  3. In the Add Connection dialog type .\SQLEXPRESS as the Server name (very important: do not forget about the dot preceding the backslash) , and select the Recipe01.OrderDatabaseContext item from the combo box beneath the Select or enter a database name option, as shown in Figure 9. Click OK and your new connection is created.

    f009

    Figure 9: Specifying the server and the database

  4. Expand the new data connection node and then its Tables node. You can see two tables there, EdmMetadata and Orders. Right-click Orders and select the Show Table Data command. The content of the Orders table is displayed, as shown in Figure 10, with the order data your program inserted into the database.

    f010

    Figure 10: The data in the Orders table

How It Works

It is amazing how many tasks this short program undertook! The code you’ve written created a database behind the scenes, and took care of inserting a record and then reading it back. But how is the whole magic done? Who is the sorcerer behind this?

This jugglery is brought to you by Entity Framework Code First. This smart component is responsible for the simplicity of this recipe. The whole story begins with the following code snippet in Program.cs:

  1. using (var context = new OrderDatabaseContext())
  2. {
  3.     var newOrder = new Order
  4.                        {
  5.                            Customer = "IntelliGrail Co.",
  6.                            OrderDate = DateTime.Now,
  7.                            Status = "NEW",
  8.                            Total = 100
  9.                        };
  10.     context.Orders.Add(newOrder);
  11.     context.SaveChanges();
  12. }

The instance of OrderDatabaseContext held in context starts the cogs of Entity Framework moving. The declaration of newOrder creates an instance of an Order entity you add to the Orders property of context in the next line. In this moment Entity Framework switches to first gear. It checkes whether the database implicitly defined by the OrderDatabaseContext exists. Because it does not found the database, it creates it (this is its default behavior). By convention, it uses the .\SQLEXPRESS instance and named the database according to the full type name of the context class.

The declaration of OrderDatabaseContext was the following:

  1. public class OrderDatabaseContext : DbContext
  2. {
  3.     public DbSet<Order> Orders { get; set; }
  4. }

From this declaration Entity Framework inferres that a table should be created to store Order instances, and uses the properties of the Order class to guess out the structure of the table.

The last operation of the first using statement is the invocation of the SaveChanges method. This operation collects all changes in the database context since it was created, and recognizes that you’ve added a single Order instance to it. It translates this addition to an INSERT database operation and places the new Order instance into the database with the INSERT statement.

Closing the using statement releases the resources held by the context instance.

The next using blocksimply reads back the inserted record from the database:

  1. using (var context = new OrderDatabaseContext())
  2. {
  3.     var order = context.Orders.FirstOrDefault();
  4.     Console.WriteLine("{0}: {1}, {2}, {3}",
  5.         order.Customer, order.OrderDate, order.Status,
  6.         order.Total);
  7. }

This time the data context class recognizes that the database already exists, and it do not want to create it. It simply translates the FirstOrDefault operation to a SQL SELECT statement to obtain the order entity you’ve inserted.

Going On

Hopefully you appreciated this recipe, because it took only a few ingredients and a short time to cook. In the next recipe you will add a little spice to this small application to make it more delicious.


Posted Jul 11 2011, 01:00 AM by inovak
Filed under:
Attachment: Recipe01.zip

Comments

Preet wrote re: EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application
on Sun, Aug 28 2011 4:13

Hi there, thanks for this tutorial. However I needed add an app.config with a connectionstrings setting before I could get the project to run. Is there something I missed please?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

 <connectionStrings>

   <add name="OrderDatabaseContext"

        connectionString="server=.;database=orderdatabase;Integrated Security=yes;"

        providerName="System.Data.SqlClient"/>

 </connectionStrings>

</configuration>

Chandradev wrote re: EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application
on Tue, Apr 3 2012 9:15

It is really excellent post. You have written in very interesting way.

Chandradev wrote re: EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application
on Mon, Apr 9 2012 14:18

Hi

is it required to download  the "Manage NuGet Packages" everytime when ever we will create the new application ?

Brecht wrote re: EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application
on Tue, Sep 4 2012 14:19

@Preet: Yes, I also needed to add a connection string to my App.config first. After that, it worked like a charm.

@Chandradev: Yes, NuGet automatically downloads and references the DLL's of the packages to your project so you don't have to manually reference them and put them in your bin folder or wherever you have them.

Ademu Anthony wrote re: EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application
on Wed, Nov 14 2012 8:49

This post is really a savior to me today. I burn the whole night trying to figure out how I can get this done. Thanks  

buy clomid no prescription wrote re: EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application
on Mon, Feb 25 2013 15:21

Im thankful for the article post. Cool.

Day 46 - Saturday September 7th 2013 | My Capstone Project Blog wrote Day 46 - Saturday September 7th 2013 | My Capstone Project Blog
on Sat, Sep 28 2013 6:05

Pingback from  Day 46 - Saturday September 7th 2013 | My Capstone Project Blog

Clash Of Clans Online Hack wrote Clash Of Clans Online Hack
on Tue, Sep 9 2014 11:08

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Call Of Duty Advanced Warfare Wall Hack wrote Call Of Duty Advanced Warfare Wall Hack
on Wed, Sep 10 2014 7:11

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

http://www.neor.wa.cz/pro_test2.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Fmonster-warlord-hack%2F%3Emonster+warlord+cheats%3C%2Fa%3E wrote http://www.neor.wa.cz/pro_test2.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Fmonster-warlord-hack%2F%3Emonster+warlord+cheats%3C%2Fa%3E
on Mon, Sep 15 2014 9:29

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

http://94.23.214.29/test/python/test.html?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Fdragon-city-hack-dragon-city%2F%3Edragon+city+hack%3C%2Fa%3E wrote http://94.23.214.29/test/python/test.html?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Fdragon-city-hack-dragon-city%2F%3Edragon+city+hack%3C%2Fa%3E
on Mon, Sep 15 2014 19:39

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

http://formazione.cidiweb.com/server_maurizio.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fconfidencegames.com%2Fgame-war-fire-age-hack%2F%3Ehttp%3A%2F%2Fconfidencegames.com%2Fgame-war-fire-age-hack%2F%3C%2Fa%3E wrote http://formazione.cidiweb.com/server_maurizio.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fconfidencegames.com%2Fgame-war-fire-age-hack%2F%3Ehttp%3A%2F%2Fconfidencegames.com%2Fgame-war-fire-age-hack%2F%3C%2Fa%3E
on Mon, Sep 22 2014 1:13

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

relevant webpage wrote relevant webpage
on Wed, Sep 24 2014 14:21

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Game Of War Fire Age Hack wrote Game Of War Fire Age Hack
on Sun, Sep 28 2014 0:52

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Call Of Duty Advanced Warfare Playstation 4 Hack wrote Call Of Duty Advanced Warfare Playstation 4 Hack
on Fri, Oct 3 2014 21:43

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

8 ball pool money hack wrote 8 ball pool money hack
on Sun, Oct 5 2014 9:40

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Boom Beach Cheats wrote Boom Beach Cheats
on Mon, Oct 6 2014 6:25

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Game of war fire age hack wrote Game of war fire age hack
on Mon, Oct 6 2014 10:17

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

http://84.19.182.90/php.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Fmegapolis-cheats%2F%3EMegapolis+Cheats%3C%2Fa%3E wrote http://84.19.182.90/php.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Fmegapolis-cheats%2F%3EMegapolis+Cheats%3C%2Fa%3E
on Tue, Oct 7 2014 0:58

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Candy Crush Saga Hack wrote Candy Crush Saga Hack
on Wed, Oct 8 2014 13:31

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

http://www.promovols.com/services/infophp.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.aaravsingh.net%2Fguestbook%2Findex.php%3Egenerateur+credit+fifa+15%3C%2Fa%3E wrote http://www.promovols.com/services/infophp.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.aaravsingh.net%2Fguestbook%2Findex.php%3Egenerateur+credit+fifa+15%3C%2Fa%3E
on Fri, Oct 10 2014 4:26

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Clash Of Clans Hack No Download wrote Clash Of Clans Hack No Download
on Sun, Oct 12 2014 21:14

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

http://www.fredteifel.de/cgi-bin/info.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Ffifa-15-coin-generator%2F%3Efifa+15+coins%3C%2Fa%3E wrote http://www.fredteifel.de/cgi-bin/info.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2Fwww.socialcheats.com%2Ffifa-15-coin-generator%2F%3Efifa+15+coins%3C%2Fa%3E
on Wed, Oct 15 2014 6:13

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

generateur credit fifa 15 wrote generateur credit fifa 15
on Wed, Oct 15 2014 23:44

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

ایرانسل wrote ایرانسل
on Sun, Nov 23 2014 6:02

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net

Traffic Racer Hack Tool wrote Traffic Racer Hack Tool
on Sun, Nov 23 2014 17:49

EF Code First Cookbook — Recipe #1: Creating a Simple Code First Application - DiveDeeper's blog - Dotneteers.net