2
votes

I am getting following exception while accessing data form database using fluent NHibernate

An exception of type 'NHibernate.HibernateException' occurred in NHibernate.dll but was not handled in user code

Additional information: Can't Parse 1 as State

I have Enum type in my employee entity.

Employee

public class Employee
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual DateTime DateOfBirth { get; set; }
    public virtual string ContactNumber  { get; set; }
    //[JsonConverter(typeof(StringEnumConverter))]
    public virtual State Status { set; get; }
    public virtual DateTime LastModify  { get; set; }
}

EmployeeMapping

public class EmployeeMap : ClassMapping<Employee>
{
    public EmployeeMap()

    {
        Table("Employee");

        Id(i => i.Id, m => m.Generator(Generators.GuidComb));

        Property(p => p.Name, m =>
        {
            m.NotNullable(false);
            m.Length(120);
        });

        Property(p => p.DateOfBirth, m => m.NotNullable(true));

        Property(p => p.ContactNumber, m =>
        {
            m.NotNullable(false);
            m.Length(12);
        });

        Property(p => p.Status, m => m.Column(y =>
        {
            y.NotNullable(true);
            y.Default(0);
        }));

        Version(v => v.LastModify, m =>
        {
            m.Column(y =>
            {
                y.NotNullable(true);
                y.Default("CURRENT_TIMESTAMP");
            });
            m.Type(NHibernateUtil.Timestamp);
            m.Generated(VersionGeneration.Never);
        });
    }       
}

State Enum

public enum State
{
    Probationer ,
    Permanent,
    Contractor
}

Please suggest me how to remove the exception.

2
Post your enum here tooAlexey Zimarev
This was discussed many times before, this is just one example stackoverflow.com/questions/12724128/…Alexey Zimarev
@AlexeyZimarev I this link they Implement ClassMap<> but in my question I am implementing ClassMapping<> . In ClassMapping I don't have such option to map enum.MANISH KUMAR CHOUDHARY
Try using enum with values, so it actually make sense to use Default(0). I mean Probationer = 0 and so on.Alexey Zimarev
I tried enum with values also but getting same parsing error.MANISH KUMAR CHOUDHARY

2 Answers

2
votes

Try this:

Property(x => x.Status, x => x.Type(typeof(State), null));
2
votes

When I tried using NHibernate Mapping by Code using the approach from Alexey or this:

Property(x => x.Command, o =>
{
  o.Type<CommandType>();
});

I got a mapping error along the lines of 'must implement IUserType. The correct way to map an enum is:

Property(x => x.Command, o =>
{
  o.Type<EnumType<CommandType>>();
});