asp.netentity-frameworkentity-framework-4entitydatasource

Displaying Navigation Properties on a GridView using EntityDataSource?


I have an EntityDataSource I've mapped to the entity Resident which includes two navigation properties (Building1, Room1). I've set my GridView to use this EntityDataSource and set the EntityDataSource Include property to Building1, Room1 so it includes these navigation properties and have added these columns to the GridView. When I run the application instead of displaying the associated navigation property it shows this: webHousingAdmin.Building How can I get it to display the actual value? Code looks like this for GridView:

        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lbl1" runat="server" Text='<%# Bind("Building1") %>' />
            </ItemTemplate>
        </asp:TemplateField>

I've gotten it to display the actual value by using the following code:

            <asp:TemplateField HeaderText="Building">
            <ItemTemplate>
                <asp:Label ID="lblBuilding" Text='<%# Bind("Building1.building_name") %>' runat="server" />
            </ItemTemplate>
        </asp:TemplateField>

But is there a simpler way to do this? This only displays the text, doesn't let me edit it...if I can do it as a boundfield that would be ideal.


Solution

  • To get something meaningful in your label you can either bind a scalar property of your Building class to the Label ...

    <asp:Label ID="lbl1" runat="server" Text='<%# Bind("Building1.Name") %>' />
    

    ... or you can overwrite ToString() of the class ...

    public class Building
    {
        public string Name { get; set; }
        public string AnotherText { get; set; }
    
        public override string ToString()
        {
            return string.Concat(Name, ", ", AnotherText); // or whatever you like
        }
    }
    

    If you bind a property to the grid which is a class the binding engine will call ToString() - and this returns only the full class name (namespace dot class name) if you don't override ToString. This explains why you only see webHousingAdmin.Building in your example.

    Edit

    Not really related to this question: But you might encounter problems if you try to bind navigation properties with Bind (and not only Eval) for bidirectional communication between datasource and grid. Probably it won't work. See this related question and answer:

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