MULTIMEDIA

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"
DefaultContainerName="NorthwindEntities"
EntitySetName="Employees">
</asp:EntityDataSource>

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"
DefaultContainerName="NorthwindEntities"
EntitySetName="Employees"
Select="it.[LastName], it.[FirstName]">
</asp:EntityDataSource>

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"
ConnectionString="name=NorthwindEntities"
DefaultContainerName="NorthwindEntities" EnableFlattening="False"
EntitySetName="Employees"
Where="" AutoGenerateWhereClause="True">
<WhereParameters>
<asp:ControlParameter ControlID="GridView1" Name="EmployeeID"
PropertyName="SelectedValue" />
</WhereParameters>
</asp:EntityDataSource>

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"
ConnectionString="name=NorthwindEntities"
DefaultContainerName="NorthwindEntities" EnableFlattening="False"
EntitySetName="Employees"
Where="" AutoGenerateWhereClause="True"
EnableInsert="True" EnableUpdate="True" EnableDelete="True">
<WhereParameters>
<asp:ControlParameter ControlID="GridView1" Name="EmployeeID"
PropertyName="SelectedValue" />
</WhereParameters>
</asp:EntityDataSource>

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.

Other  
  •  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
  •  
    Video
    Top 10
    Mobile Application Security : The Apple iPhone - Push Notifications, Copy/Paste, and Other IPC
    Exploring the T-SQL Enhancements in SQL Server 2005 : The WAITFOR Command
    Parallel Programming with Microsoft .Net : Parallel Aggregation - Variations
    Optimizing an Exchange Server 2010 Environment : Analyzing Capacity and Performance
    Programming .NET Security : Hashing Algorithms Explained
    Sharepoint 2007: Specify Your Colleagues
    Algorithms for Compiler Design: THE NFA WITH ∈-MOVES
    Choosing The Right Parts For Your Build (Part 1) - Picking the perfect processor
    Choosing The Right Parts For Your Build (Part 5) - Choosing your case & Picking the right storage
    SQL Server 2008 : Leveraging the Microsoft Sync Framework
    Most View
    Legal Trouble with Social Networks (Part 1)
    The choices of mobile computing for SOHO users (part 2)
    Infrastructure Security: The Application Level
    Sharepoint 2007: Create a New List Item
    SQL Azure Data Access
    Getting Started with MySQL Enterprise & MySQL Enterprise Components
    iPhone Application Development : Using Advanced Interface Objects and Views - User Input and Output
    How to Protect Your Mobile Devices
    Joomla! Blogging and RSS Feeds : Commenting anyone?
    The Second BlackBerry Developers Conference Asia (Part 2)
    Windows Azure : Understanding the Blob Service
    Windows Server 2008 : Understanding the Identity Management for UNIX Components
    Migrating from Legacy SharePoint to SharePoint Server 2010 : Using Visual Upgrade
    Designing and Implementing Mobility in Exchange Server 2010 : Securing Access to ActiveSync Using Internet Security and Acceleration (ISA) Server 2006
    SQL Server 2008 : Explaining Advanced Query Techniques - Creating CTEs
    Configuring Server Roles in Windows 2008 : New Roles in 2008
    Mass Effect Infiltrator
    iPhone 3D Programming : Anti-Aliasing Tricks with Offscreen FBOs (part 1) - A Super Simple Sample App for Supersampling
    Changes in Windows Vista Affecting SDI
    Search for a File or Directory