6

Table Model:

public class UserOwnerShip
{
    public virtual int Id { get; set; }
    public virtual User User { get; set; }
    public virtual City City { get; set; }
    public virtual Company Company { get; set; }
    public virtual UserRole UserRole { get; set; }
    public virtual DateTime RegistryDate { get; set; }
    public virtual bool IsActive { get; set; }
}

Mapping:

internal class UserOwnerShipMap : ClassMap<UserOwnerShip>
{
    public UserOwnerShipMap()
    {
        Id(x => x.Id);
        Map(x => x.IsActive);
        Map(x => x.UserRole).CustomType(typeof(int));
        Map(x => x.RegistryDate);

        References(x => x.User).Not.Nullable();
        References(x => x.City).Nullable();
        References(x => x.Company).Nullable();
    }
}

My EnumConvention Class :

public class EnumConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum ||
            (x.Property.PropertyType.IsGenericType &&
             x.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) &&
             x.Property.PropertyType.GetGenericArguments()[0].IsEnum)
            );
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(target.Property.PropertyType);
    }
}

And UserRole Enum

public enum UserRole
{
    User,
    Operator,
    Manager,
    Manager,
    Admin
}

And my nhibernate config section :

....().Conventions.AddFromAssemblyOf<EnumConvention>())

So when I query :

    IList<UserOwnerShip> userOwnerShip = session.QueryOver<UserOwnerShip>()
                                                    .Where(u => u.UserRole == UserRole.Owner)
                                                    .Where(u => u.IsActive)
                                                    .List<UserOwnerShip>();

I got exception:

Type mismatch in NHibernate.Criterion.SimpleExpression: UserRole expected type System.Int32, actual type XXX.XXX.UserRole (which is enum type class)

1 Answer 1

8

If you want to store the int value of the enum, the mapping is simply:

Map(x => x.UserRole).CustomType<UserRole>();

There's no need for the EnumConvention.

Sign up to request clarification or add additional context in comments.

1 Comment

The times it is easier than you thought don't make up for the times it is harder, so enjoy this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.