Columns of two related database tables in one ASP.NET GridView with EntityDataSource

OK, much too many hours later I found the solution myself:

Option 1:

It is possible to use the select property in the EntityDataSource which allows to create arbitrary projections of data from several related entities/database tables (in my case: OrderID from Order entity and City from the
Address entity)

Drawback: Using select in the EntityDataSource makes using Insert, Update and Delete in the GridView impossible!

Option 2:

The EntityDataSource must have the include property to include the related address property along with the queried orders. The markup looks likes this:

<asp:EntityDataSource ID="EntityDataSourceOrders" runat="server" 
    ConnectionString="name=MyEntitiesContext" 
    DefaultContainerName="MyEntitiesContext" 
    EntitySetName="Order" Include="Address"
    EnableDelete="True" EnableInsert="True" 
    EnableUpdate="True">
</asp:EntityDataSource>

Then the columns collection of the GridView can have a template field like this:

<asp:TemplateField HeaderText="City" >
  <ItemTemplate>
    <asp:Label ID="LabelCity" runat="server" Text="<%# Eval("Address.City") %>">
    </asp:Label>
  </ItemTemplate>
</asp:TemplateField>

Here Eval is important. Bind does not work. Also using a BoundField as a column…

<asp:BoundField DataField="Address.City" HeaderText="City" />

… is NOT possible. So it is not possible in the GridView to edit the City (which makes sense because its a related field belonging to another table and perhaps to many other orders). But it is possible to edit flat fields of the order entity and also the “AddressID” of the order to assign another address.

Leave a Comment