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

前端 未结 1 816
[愿得一人]
[愿得一人] 2020-12-03 03:34

I have two SQL Server tables with Primary Keys (PK) and a Foreign Key (FK) linking the two tables:

1) Table \"Order\"

OrderID, int, PK  
AddressID, int, FK
         


        
相关标签:
1条回答
  • 2020-12-03 04:04

    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.

    0 讨论(0)
提交回复
热议问题