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.
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).
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.
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.