ASP.NET 4 : LINQ and the Entity Framework - The EntityDataSource

2/13/2012 5:24:35 PM
Much like the SqlDataSource control, when you use the EntityDataSource control, you don't need to write any code. But the EntityDataSource control goes one step further—not only can you avoid writing C# code, but you can avoid the messy details of writing SQL queries to select and update data. This makes it a perfect tool for small or medium-scale applications and applications that don't need to be carefully tuned to get every last ounce of performance. On the other hand, it's also sure to exasperate database purists who prefer to have complete control over every detail.

1. Displaying Data

To get a feel for the capabilities and overall goals of the EntityDataSource, it's worth building a simple example. In the following example you'll see how to build the web page shown in Figure 1, which allows you to insert, delete, and update records in the Employees table.

Figure 1. Managing a table with the EntityDataSource

Assuming you've already created your data model, the next step is to add the control you want to use to display your data. In this example, two controls are used—a GridView that allows you to select an employee and a DetailsView that allows you to change it, remove it, or create a new one. You can add both controls straight from the Toolbox and use the AutoFormat feature to give them a pleasant color scheme.

The third ingredient is the data source that links the context object to your data controls. In this example, you'll need two data source controls—one that retrieves all the employee records (for the GridView) and one that retrieves a single employee record (for the DetailsView). The latter will also perform the editing, inserting, and deleting operations.

To create your first data source, drop an EntityDataSource control onto your web page. The quickest way to configure it is to use the wizard (select the data source control, click the arrow in the top-right corner, and choose Configure Data Source). The wizard has just two steps. The first step displays all the derived ObjectContext classes in your project (such as NorthwindEntities) and prompts you to choose one.

The second step asks you what columns you want to include. To include all, choose the Select All item at the top of the list (Figure 2).

Figure 2. Choosing columns

When you've finished the wizard, you'll end up with a fairly straightforward control tag, like this:

<asp:EntityDataSource ID="sourceEmployees" runat="server"
ConnectionString="name=NorthwindEntities" EnableFlattening="False"

The ConnectionString property indicates the name of the connection string that's stored in the web.config file. The DefaultContainerName indicates the name of the data model that you're using, and the EntitySetName indicates the collection you're binding from the context object. This data source assumes you're including all the fields (although you won't necessarily be displaying all these fields, depending on how you've configured your data display control).

If you selected a subset of columns in the second step of the wizard , you'll also see a Select property that defines a projection, like this:

<asp:EntityDataSource ID="sourceEmployees" runat="server"
ConnectionString="name=NorthwindEntities" EnableFlattening="False"
Select="it.[LastName], it.[FirstName]">

If the syntax looks a little strange, just remember that the EntityDataSource uses the name it for the data object when it performs a projection. In other words, the EntityDataSource shown earlier uses an expression that would be written like this:

Dim matches = From it In employees
Select New
With {.LastName = it.LastName, .FirstName = it.FirstName}

Simply set the GridView.DataSourceID property to sourceEmployees. Next, make sure that the GridView supports selection. The DataKeyNames property should be set to EmployeeID, and a Select column should be visible in the grid (to add it, check the Enable Selection option in the GridView smart tag or set the GridView.AutoGenerateSelectButton property by hand).

The DetailsView shows the currently selected employee in the grid. You learned how to create this design with the SqlDataSource, but the EntityDataSource works a bit differently because it doesn't allow you to define the Select command directly. To start, begin by creating a new EntityDataSource that has the same characteristics as the first one. Then, you need to build the where operator for the LINQ expression by setting the EntityDataSource.Where property. This will filter the query to include just the single matching employee entity.

The easiest way to build this part is to select the EntityDataSource object on the design surface of your page, find the Where property in the Properties window, and then click the ellipsis (...) button. This opens a window named Expression Editor. Make sure the "Automatically generate the Where expression" check box is selected at the top of this window. Then, click the Add Parameter button, and enter the name of the field you want to use for your filter condition (in this case, it's EmployeeID). In the Parameter Source drop-down list (to the bottom right), choose Control. In the ControlID list (just underneath), choose your GridView (in this case, that's GridView1). Figure 3 shows the completed dialog box, with all the information in place.

Figure 3. Filtering out a single employee

This data source attempts to find an employee with an EmployeeID that matches the selected value in the GridView. Here's the complete markup that's generated:

<asp:EntityDataSource ID="sourceSingleEmployee" runat="server"
DefaultContainerName="NorthwindEntities" EnableFlattening="False"
Where="" AutoGenerateWhereClause="True">
<asp:ControlParameter ControlID="GridView1" Name="EmployeeID"
PropertyName="SelectedValue" />

Now, when you select an employee in the GridView, the full details will appear in the DetailsView.

2. Editing Data

The final step in this example is to configure the DetailsView and second EntityDataSource to support update, insert, and delete operations. To enable these, simply select the sourceSingleEmployee on the design surface of your page and set the EnableInsert, EnableDelete, and EnableUpdate properties to True using the Properties window. Alternatively, you can use the check boxes in the Configure Data Source Wizard, as shown in Figure 3. Either way, this simply sets a few similarly named properties in the EntityDataSource control tag:

<asp:EntityDataSource ID="sourceSingleEmployee" runat="server"
DefaultContainerName="NorthwindEntities" EnableFlattening="False"
Where="" AutoGenerateWhereClause="True"
EnableInsert="True" EnableUpdate="True" EnableDelete="True">
<asp:ControlParameter ControlID="GridView1" Name="EmployeeID"
PropertyName="SelectedValue" />

Remarkably, this is all you need to complete the example. The EntityDataSource will now automatically use the NorthwindEntities to perform these record operations. When deleting a record, it uses the DeleteObject() method you considered earlier. When adding a record, it creates a new Employee entity object and calls AddObject() to insert it into the collection. When modifying a record, it simply sets the corresponding properties. No matter which operation you're using, it ends by calling SaveChanges() to apply the new data.

  •  DirectX 10 Game Programming : Direct3D Fonts
  •  DirectX 10 Game Programming : Adding Text & Creating a Font System Using Sprites
  •  Adobe InDesign CS5 : Importing Graphic Objects (part 3) - Using the Image Import Options Dialog Box
  •  Adobe InDesign CS5 : Importing Graphic Objects (part 2) - Importing Graphics with the Place Command
  •  Adobe InDesign CS5 : Importing Graphic Objects (part 1) - Understanding Adobe Bridge
  •  Building a WPF Application without XAML (part 2)
  •  Building a WPF Application without XAML (part 1)
  •  iPhone 3D Programming : Drawing an FPS Counter (part 2) - Rendering the FPS Text
  •  iPhone 3D Programming : Drawing an FPS Counter (part 1) - Generating a Glyphs Texture with Python
  •  Programming with DirectX : Game Input - XInput
  •  Programming with DirectX : Game Input - Win32 Input
  •  Introducing Windows Presentation Foundation and XAML : Investigating the WPF Assemblies
  •  Introducing Windows Presentation Foundation and XAML : The Motivation Behind WPF & The Various Flavors of WPF
  •  Microsoft XNA Game Studio 3.0 : Getting the Date and Time
  •  Microsoft XNA Game Studio 3.0 : Text and Computers
  •  Silverlight Recipes : Managing Embedded Resources
  •  Silverlight Recipes : Managing XAML Resources
  •  Silverlight Recipes : Updating the UI from a Background Thread
  •  Programming with DirectX : Sound in DirectX - XAudio2
  •  Programming with DirectX : Sound in DirectX - XACT3 (part 2) - XACT3 Demo
    Top 10
    The Human Touch
    Some Cool Apps From Various Flatforms To Make Your Life Easy
    A Bite of Apple iOS 6
    “TU ME” …vs Skype and Whatsapp.
    Wappwolf Dropbox Automator
    Winzip 16.5 Pro
    Attack Of The Killer Wifi
    Bridge Camera – A Complete Buyer's Guide! (Part 4 ) : Fujifilm Finepix HS20, Nikon Coolpix P500, Canon Powershot SX40 HS, Sony Cyber-Shot HX 100V, Panasonic Lumix FZ150
    Bridge Camera – A Complete Buyer's Guide! (Part 3)
    Bridge Camera – A Complete Buyer's Guide! (Part 2)
    Most View
    Programming the Mobile Web : Widgets and Offline Webapps - Platforms (part 3) - webOS & Android
    Fallen IT Giants
    Programming the Mobile Web : Geolocation and Maps - Showing a Map
    The Benefits of Facebook Marketing
    Windows Home Server Installation and Configuration
    SQL Server 2008 : Transact-SQL Programming - The max Specifier
    Microsoft XNA Game Studio 3.0 : Getting Player Input - Adding Vibration
    Safeguarding Confidential Data in SharePoint 2010 : Examining Supported Topologies
    Registry in Windows Vista
    Silverlight Recipes : Managing Embedded Resources
    SQL Server 2008 : Working with Multiple-Source Queries - OpenQuery, OpenRowSet, and OpenDataSource Explained
    Microsoft XNA Game Studio 3.0 : Displaying Images - Using Resources in a Game (part 2) - Positioning Your Game Sprite on the Screen
    The tiny miracle of microSD cards (Part 2)
    Windows 7 : Windows Driver Foundation Architecture (part 1)
    iPhone 3D Programming : Blending and Augmented Reality - Rendering Anti-Aliased Lines with Textures
    Macs no longer safe from virus attacks
    SQL Server 2008 : T-SQL Tips and Tricks (part 2) - Using CONTEXT_INFO & Working with Outer Joins
    iPhone Application Development : Creating User Interfaces
    Create virtual desktop with nSpaces (Part 1)
    Buying Guide: CPU Cooling Equipment (Part 5) - Antec KUHLER H2O 620,Arctic Cooling Freezer i30,Cooler Master Hyper 612 PWM