We found a problem when having Nullable Enum values in our DDS objects. We got an error “Invalid cast from ‘System.Int32’ to ‘RoleData.MyEnum’.” when we tried to iterate through our repository.
Others seem to have the same problem as well.
According to Paul Smith there seems to be some problems, I didn’t get the e-mail response myself so I must get back with more details.
This is my solution, using a TypeHandler, had totally forgotten about that part in the DDS Example Package.
public class EnumTypeHandler : ITypeHandler
{
//From int to enum
public object FromDatabaseFormat(string propertyName,
object propertyValue,
Type targetType, Type ownerType)
{
if (propertyValue == null)
return null;
Type valueType = targetType;
if (IsNullable(targetType))
{
valueType = Nullable.GetUnderlyingType(targetType);
}
if (valueType.IsEnum)
{
string stringValue = Convert.ToString(propertyValue);
return Enum.Parse(valueType, propertyValue.ToString());
}
return propertyValue;
}
//returns int type
public Type MapToDatabaseType(Type type)
{
if (type.IsEnum)
{
if(IsNullable(type))
return typeof(int?);
return typeof(int);
}
return type;
}
//convert enum to int
public object ToDatabaseFormat(string propertyName,
object propertyValue,
Type ownerType)
{
if (propertyValue == null)
return null;
if (propertyValue is Enum)
return Convert.ToInt32(propertyValue);
return propertyValue;
}
private bool IsNullable(Type type)
{
return (type.IsGenericType && type.GetGenericTypeDefinition()
.Equals(typeof(Nullable<>)));
}
}
It only takes care of int Enums at the moment but it’ll do.
And in EPiServer FirstBeginRequest I added the Handler by adding:
if (!GlobalTypeHandlers.Instance.ContainsKey(enumType))
GlobalTypeHandlers.Instance.Add(enumType, new EnumTypeHandler());
Where enumType is each Enum I need to handle in my DDS object.