Databases Reference
In-Depth Information
public enum EmployeeType: byte
{
[Display(Name = “Full-time”)] Fulltime = 0,
[Display(Name = “Part-time”)] PartTime = 1,
[Display(Name = “Temporary”)] Temporary = 2
}
NOTE
Reusing an existing .NET framework type is always better when it fits your needs
because it helps keep the solution smaller and simpler. In this example, reusing the
DisplayAttribute
to provide display names for enum items offers not only consis-
tency with entity properties, but also allows you to take advantage of the built-in local-
ization support and use additional display name properties, such as the
ShortName
and
Description
. However, always be cognizant of the side effects from reusing a type
for an unintended purpose. The
AutoGenerateField
and
AutoGenerateFilter
proper-
ties of
DisplayAttribute
will not be applicable to enum items, possibly causing
confusion for other developers. In this scenario, the benefits of reuse and consistency
outweigh the added complexity of creating a new attribute. However, use your own judg-
ment to make similar tradeoffs in your projects.
Having decided on how display names of enum items will be specified in the model, you
now need to modify the
Enumeration.ascx
and
Enumeration_Edit.ascx
field templates to
access the additional metadata. To make this task easier, as well as to enable reuse of this
logic in additional field templates (you might need another field template that displays a
list of radio-buttons instead of a drop-down list), the sample solution implements it in a
new base class with the two enumeration field templates to inheriting from it.
Listing 11.1 shows the complete source code of the new base class, called
UnleashedEnumerationFieldTemplate
to follow the naming convention established in
this topic. This class inherits from the
UnleashedFieldTemplate
(a class introduced in
Chapter 10) and overrides the
FieldValueString
property and the
PopulateListControl
method inherited from the ultimate base class of field templates—the
FieldTemplateUserControl
provided by Dynamic Data.
As you are reviewing the implementation of this class, notice that the
BuildEnumDictionary
method is responsible for collecting the metadata information describing a given enum
type. It uses reflection API to examine each item defined in the enum type, determine its
display name, and store the enum names and values in an
OrderedDictionary
object. This
specialized collection class was chosen because, on one hand, you need a dictionary to
support fast lookup of a display name based on an enum value. On the other hand, you
want to preserve the original order of enum items when showing their display names in a
drop-down list. The
OrderedDictionary
class from the
System.Collections.Specialized
namespace is the only dictionary class provided by the .NET framework that also preserves
the order of its items.