Handle exception from nHibernate EnumStringType when enum values don't match string values

Viewed 1515

Her is my situation where the enum values are stored as string in the Db. While retrieving I am getting an exception trying to convert string to enum using mytype that has the base class as EnumStringType.

Here is the error I am getting:

NHibernate.HibernateException : Can't Parse Enum4 as MyEnum

For example: The value coming from database is: "Enum4"

Valid enum values as per the code for MyEnum are:

Enum1 Enum2 Enum3

Somehow Enum4 got introduced in the Db before the code has accommodated the change. (I know crazy stuff happens)

The exception is normal because my Enum does not have this value coming from the database. But I don't want the user to get an exception. Instead default to the first value. (I agree this is not OK for some cases, but it is prevents exception which is more severe in my case)

If I am correct, GetInstance is the method that does this conversion from string to enum. Is there a TryGetXXXX of some sort to overcome this issue or how to solve it?

Thanks for your time!

Here is the Enum code I am playing with to address this issue:

public class EnumMappingBase : EnumStringType
{
    public EnumMappingBase(Type type)
        :base(type)
    { 

    }

    public override object GetInstance(object code)
    {
        return base.GetInstance(code); // Here is where I get the exception. 
        // I am thinking this is where capturing the exception and defaulting must happen. 
        // I wish I had a TryGetInstance() here or may be it is there and I am not aware.
    }

    public override object GetValue(object code)
    {
        return base.GetValue(code);
    }

}

public enum MyEnum
{
    Enum1,
    Enum2,
    Enum3
}

public class MyEnumType : EnumMappingBase
{
    public MyEnumType()
        : base(typeof(MyEnum))
    {

    }
}
2 Answers
Related