Binding Entity Framework Navigation Properties

I’ve been playing around with Entity Framework since the release of .NET 4 and come across a few strange behaviors.  One of the most troublesome has been when attempting to bind a related entity to a column in an ASP.NET GridView control.  In the book Pro Entity Framework 4.0, the author suggestions handling the GridView’s OnDataBound event to intercept the rendering of cells with navigation properties.  I’ve found a much simpler method that is not without its limitations, but for most people should do just fine and perform better as well.

Let’s assume we are working with the tired example of orders and customers.  If we want to bind a GridView to a list of orders and display the associated customer, the intuitive approach is to set the DataField attribute of a BoundColumn to “Customer.Name”.  This will result in the GridView displaying the name of the generated object type instead of any data relevant to the customer instance.  My quick fix is to override the ToString() method in a partial class file for the Order entity as follows:

public partial class Order {
    public override System.String ToString() {
        return (this._Customer.Name);
    }
}

When you use the Customer navigation property to bind to a column in the grid you will see the customer’s name instead of the underlying class type name.  The major limitation here is that you have to choose only one data element to be displayed.  If you wanted to show the customer’s account number or year-to-date sales you’d need to use a different approach.  For simple binding scenarios, though, this will get you by.

× Comments are closed.