Improving the FK field display: Showing two fields in Foreign Key columns

 

The default scaffold of the CustomerAddress table in the AdventureWorksLT database poses a problem: Dynamic Data (DD) defaults to using the first string field in the referenced table. In this case, the first string field is the Title field (Mr,Ms, and so on).  The image below shows the problem with the FilterRepeater drop down list and Customer column elements.

We can take a first step toward fixing this issue by creating and annotating a partial class for the Customer entity. The code below now displays the LastName field for the customer entity. The DisplayColumn attribute tells referring entities which column to use for display instead of the Foreign Key field.

  [DisplayColumn("LastName")]
 [MetadataType(typeof(CustomerMetaData))]
 public partial class Customer {
      public class CustomerMetaData {
   }
 }

While the resulting view is an improvement, it’s not there yet. Note that it doesn't distinguish between the customers with non-unique last names, such as Adams or Liu.

 

To fix this, we overload the ToString method for the Customer partial class as shown below:

 // [DisplayColumn("LastName")]
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer {

     public override string ToString() {
         return LastName.ToString() + ", " + FirstName.ToString();
     }

     public class CustomerMetaData {

}

The resulting display gets it right: the code now shows the correct field, and it distinguishes between David, Jinghao and Kevin Liu.

Special thanks to David Ebbo for recommending the ToString() approach and Phil Haack for granting me blog dibs.