Getting to Know the Entity Framework

  • 8/15/2013

Developing a simple Entity Framework example

The best way to begin learning about the Entity Framework is to use it. This example won’t do anything too spectacular. In fact, it’s downright mundane, but it does reflect a process that many developers use to experiment with the Entity Framework. In this case, you’ll use the model-first technique to create an example application. Remember that in the model-first approach, you begin by creating a model that’s then added to the database, rather than relying on an existing database to define the model. The model-first technique has the advantage of allowing you to create and manipulate a database that won’t have any impact on anyone else, so you’re free to experiment as much as you want.

The example will start with a Windows Forms application. You’ll create the model needed to make the database work with SQL Server Express (installed automatically on your system), and then use the resulting model to create a functional application. You’ll test the application by managing some data you create with it. The entire process will take an amazingly short time to complete, as described in the following sections.

Starting the Entity Data Model Wizard

The first step is to create the database model. You can perform this task using a number of methods, most of which developers never use. The easy method is to start the Entity Data Model Wizard and have it do the work for you. That’s the approach this example takes, as described in the following steps (you can find this project in the \Microsoft Press\Entity Framework Development Step by Step\Chapter 01\SimpleEF folder of the downloadable source code):

  1. Start Visual Studio 2012.

  2. Choose File | New | Project to display the New Project dialog box, as shown here:

  3. Type SimpleEF in the Name field and click OK. You’ll see a new Windows Forms project.

  4. Choose View | Other Windows | Data Sources. You’ll see the Data Sources window, as shown here:

  5. Click Add New Data Source. You’ll see the Data Source Configuration Wizard dialog box. The wizard asks you to select a data source type, as shown here:

  6. Select Database and click Next. The Data Source Configuration Wizard asks you to select a database model, as shown here:

  7. Choose Entity Data Model and click Next. The Data Source Configuration Wizard asks you to choose the model content, as shown here:

  8. Choose Empty Model and click Finish. You’ll see Visual Studio perform a few tasks. When you have the default User Access Control (UAC) set up, you’ll see a Security Warning dialog box telling you that running the script required to generate the Entity Data Model could harm your system. If you see this message, check the Do Not Show This Message Again option and click OK to continue generating the Entity Data Model. It’s during this phase of the procedure that you’ll see the Entity Data Model Wizard perform the tasks required to generate an empty model for you. After a few additional moments, you’ll see a blank Entity Data Model Designer window like the one shown here:

Solution Explorer also shows the result of adding the new data source. Notice the Model1.EDMX file shown in the screen shot. This file contains the conceptual model, store model, and model mappings. Each feature uses the language (CSDL, SSDL, and MSL) required for that part of the Entity Framework data.

Using the Entity Data Model Designer

After you add an Entity Data Model to your application, you can begin adding items to it from the toolbox—just as you do when adding controls to your application. For example, if you want to add an entity to the model, you drag and drop it onto the Entity Data Model Designer. The toolbox, shown here, contains the elements described earlier in the chapter.


You’ll begin working with a model by adding an Entity to it and then configuring the Entity as needed. The example uses a simple Entity named Customer with just a few properties that describe the resulting Customer object. In this case, you’ll use the following properties:

  • First Name (FirstName)
  • Last Name (LastName)
  • First Address Line (AddressLine1)
  • Second Address Line (AddressLine2)
  • City (City)
  • State/Province (State_Province)
  • ZIP/Postal Code (ZIP_Postal_Code)
  • Region/Country (Region_Country)
  1. Drag an Entity object from the toolbox to the Entity Data Model Designer. You’ll see a new square added containing a blank entity, as shown here:


    Notice that the designer automatically adds an Id property for you. This property uniquely identifies a particular entry.

  2. Right-click the Entity1 object and choose Rename from the context menu. The Entity1 entry changes to a text box. Type Customer and press Enter.

  3. Right-click the Id property and choose Rename from the context menu. The Id property changes to a text box. Type CustomerID and press Enter.

  4. Right-click the Customer object and choose Add New | Scalar Property from the context menu. You’ll see a new property added with the name as a text box.

  5. Type FirstName (the value shown in parentheses in the previous list) and press Enter.

  6. Perform steps 4 and 5 for all of the properties described earlier in this section. When you’re finished, your entity should look like this one:


    At this point, you could select any of these entity properties and change their properties using the Properties window, just as you would with any application feature. For example, you could change the Type property to any of the supported data types. However, for the purposes of this example, you don’t actually need to change anything.

Notice that the default Entity object color is blue. When working with a complex design, you may want to color code the entities to make them easier to identify. For example, you may want to color customer entities blue and employee entities red. Color coding can make it easier to find the specific entity group you want. To change the color of an entity, select the entity in the designer and change the Fill Color property in the Properties window.

Working with the mapping details

At this point, you’ve defined a model for the example application. Right-click the Customer entity and choose Validate from the context menu. The IDE tells you that entity Customer isn’t mapped, as shown here:

Creating a model doesn’t create the required mapping. In fact, the database you just created doesn’t exist at all. The model for the database exists, but you still need to tell Visual Studio to interact with the database manager (SQL Server Express in this case) to create the physical database and develop a map between your model and the logical database.

  1. Right-click the Customer entity and choose Generate Database From Model on the context menu. You’ll see the Generate Database Wizard dialog box, as shown here:

  2. Click New Connection. You’ll see the Choose Data Source dialog box shown here:

  3. Select Microsoft SQL Server and then click Continue. You’ll see a Connection Properties dialog box like the one shown here:

  4. Choose the name of the server you want to use in the Server Name drop-down list box.

  5. Type TestCustomer in the Select Or Enter A Database Name field.

  6. Click OK. You’ll see a dialog box telling you that the database doesn’t exist. Visual Studio asks permission to attempt to create the database for you.

  7. Click Yes. Visual Studio creates the new database for you. This is a blank database—it doesn’t contain any tables, views, indexes, or anything else normally associated with a database. You’ll return to the Generate Database Wizard dialog box. However, now the connection information is filled in.

  8. Click Next. The Generate Database Wizard creates the Data Definition Language (DDL) script required to create everything in the model you designed, as shown here. You can scroll through this script to see the SQL statements used to make your model a real database and associated table.

  9. Click Finish. You’ll see the script, Model1.EDMX.sql, open. It hasn’t executed yet. All that the Generate Database Wizard has done is create the script required to make your database model functional.

  10. Choose SQL | Transact-SQL Editor | Execute. You’ll see a connection dialog box where you can enter the information required to connect to the SQL Server instance you’ve selected.

  11. Enter any required credentials and click Connect. Visual Studio connects to the database manager and executes the SQL script it created. At this point, your database is ready for use. Notice that you didn’t have to access the database manager yourself or create any scripts by hand.

Using the resulting framework to display data

Now that you have a database to use—a database generated from a model you created—you might want to see the database in action. There are a number of ways to accomplish the task, but for this first sample, it’s probably best to try something easy. The one piece of information you absolutely need to know before you start is that the model you created earlier also generated code. Part of this code is the creation of a container that you use to access the database. The container class always starts with the name of the model, followed by the word container. For this example, this means that the name of the container class is Model1Container.

Nothing else you do with the Entity Framework is going to be outside your experience if you’ve worked with collections in the past. The following steps create a simple application that will test just a few of the features that this model provides. Chapter 2 “Looking more closely at queries,” will help you start performing more complex tasks.

  1. Add four buttons to the Windows Forms application you created at the outset of this example, and name them btnCount, btnAdd, btnDelete, and btnQuit. Here’s an example of the simple form as it appears in the downloadable source:

  2. Right-click the Form1.cs entry in Solution Explorer and choose View Code from the context menu. You’ll see the Code Editor. Add a reference to the model container and instantiate it in the form’s constructor, as shown here:

    // Define a container to hold the database information.
    Model1Container ThisContainer;
    public Form1()
       // Instantiate the container.
       ThisContainer = new Model1Container();

    ThisContainer contains a reference to all of the elements found in the model. In this case, the model only contains a reference to one table, Customers. However, in a production application, you could use ThisContainer to access every table, view, index, or other feature in the database.

  3. Double-click Count. Visual Studio creates an event handler for you. Add the following code to the event handler:

    private void btnCount_Click(object sender, EventArgs e)
       // Display the number of database records.
       MessageBox.Show("There are " +
          ThisContainer.Customers.Count().ToString() +
          " Records.");

    The container for all of the database elements is found in ThisContainer. Within the container is a table named Customers. The Count() method outputs the number of records in the specified table.

  4. Double-click Add and add the following code to the resulting event handler:

    private void btnAdd_Click(object sender, EventArgs e)
       // Create a new record.
       Customer ThisCustomer = ThisContainer.Customers.Create();
       // Add some random data.
       Random ThisValue = new Random(DateTime.Now.Millisecond);
       ThisCustomer.FirstName = ThisValue.Next().ToString();
       ThisCustomer.LastName = ThisValue.Next().ToString();
       ThisCustomer.AddressLine1 = ThisValue.Next().ToString();
       ThisCustomer.AddressLine2 = ThisValue.Next().ToString();
       ThisCustomer.City = ThisValue.Next().ToString();
       ThisCustomer.State_Province = ThisValue.Next().ToString();
       ThisCustomer.ZIP_Postal_Code = ThisValue.Next().ToString();
       ThisCustomer.Region_Country = ThisValue.Next().ToString();
       // Add a new record.
       // Inform the user.
       MessageBox.Show("Added " + ThisCustomer.CustomerID.ToString());

    The example begins by creating a new Customer record, ThisCustomer. It then fills the fields with random numeric values. The content is simply there to make it easy to view the record information later.

    In order to add the new record to the database, the example calls the ThisContainer.Customers.Add() method. This method requires a Customer object as input. The changes won’t take effect until the application calls ThisContainer.SaveChanges(). You need to make sure your code calls the SaveChanges() method regularly; otherwise, you risk losing application data. Finally, the application shows the record number added to the application.

  5. Double-click Delete and add the following code to the resulting event handler:

    private void btnDelete_Click(object sender, EventArgs e)
       // Obtain the first record.
       Customer ThisCustomer = null;
       if (ThisContainer.Customers.Count() > 0)
          ThisCustomer = ThisContainer.Customers.First();
          // Display an error message if there are no records to delete.
          MessageBox.Show("No Records to Delete");
       // Delete it.
       // Inform the user.
       MessageBox.Show("Deleted " + ThisCustomer.CustomerID.ToString());

    A production application would have a lot more checks than this one does, but the code begins by checking whether there are any records to delete in the Customers table. If not, the event handler exits after providing an error message.

    There are a number of ways to obtain a record from the Customers table. For that matter, you might simply want to search for a particular record based on some criterion and delete all those that match. In this case, the code uses the ThisContainer.Customers.First() method to obtain a copy of the first record in the table. The code then calls ThisContainer.Customers.Remove() to remove the record and ThisContainer.SaveChanges() to make the changes permanent. The code then informs the user about the deletion and displays the ID of the customer it deleted.

  6. Double-click Quit and add the following code to the resulting event handler:

    private void btnQuit_Click(object sender, EventArgs e)
       // Save the database.
       // End the program.

    One task you should always perform before you exit the application is to save the database changes one more time—just to ensure that none of the changes are lost. After the code calls ThisContainer.SaveChanges(), it exits by closing the form.

  7. Click Start and try some of the buttons. For example, click Count and you’ll see the current record count (0 if there are no records). Click Add and you’ll see the identifier of the customer that the application has added. Likewise, click Delete and you’ll see the identifier of the customer that the application has deleted. Make sure you end up with at least one record in the database.

  8. Choose View | Server Explorer. You’ll see the Server Explorer window shown here:

  9. Drill down into the TestCustomer.dbo\Tables\Customers entry, as shown in the preceding image. Notice that the complete table structure is precisely as you designed it.

  10. Right-click Customers and choose Show Table Data from the context menu. You’ll see a new window appear with the data from the table as shown here (your data will most definitely differ from mine because the data is randomly generated in this application):

    This environment is fully interactive, so you can use it to check the results of your database experiments. More importantly, you can use it to modify the data as necessary to meet test requirements.

  11. Click Quit to end the application. You can always experiment with this application later.