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

喜欢而已 提交于 2019-11-27 13:12:50

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!