Type Converters

Marr DataMapper supports enums via Type Converters. Type converters are classes that implement the IConverter interface:

public interface IConverter 
	object FromDB(ColumnMap map, object dbValue); 
	object ToDB(object clrValue); 
	Type DbType { get; } 

IConverter objects can be registered for a given datatype in the MapRepository singleton. This allows you to have direct control over the data being ushered to and from the database. The example below registers one of the built-in converters, "BooleanYNConverter" that will affect all boolean values. This would convert a boolean true/false to 'Y'/'N' respectively (this converter is useful when using Oracle, since it does not have a boolean input parameter). This affects all boolean fields marked with the Column attribute, and all boolean parameters added using the AddParameter method.

// Register a BooleanYNConverter 
MapRepository.Instance.RegisterTypeConverter(typeof(bool), new Converters.BooleanYNConverter());

Enum Support via Type Converters

Enum support is as simple as registering one of the two built-in Enum converters.
The EnumIntConverter will convert enums to their int form.
The EnumStringConverter will convert enums to their string form.
If you want to register an enum converter that will be applied to all enums, you can register it to "typeof(Enum)". Alternatively, you could specific types of enums to use a specific converter. Specific registrations will take precedence over the wildcard "typeof(Enum)" registrations.

Note: the EnumStringConverter is automatically registered by default to handle enums, so the step below is not necessary to handle enums unless you want to use a different IConverter instead.
// Register a BooleanYNConverter 
MapRepository.Instance.RegisterTypeConverter(typeof(Enum), new Converters.EnumStringConverter());

Last edited Jan 26, 2015 at 3:52 AM by jmarr, version 1


No comments yet.