Fluent NHibernate(ASP.NET MVC)中的枚举类型不匹配问题

6

表格模型:

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; }
}

映射:

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();
    }
}

我的EnumConvention类:

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);
    }
}

用户角色枚举

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

我的nhibernate配置部分如下:
....().Conventions.AddFromAssemblyOf<EnumConvention>())

所以当我查询时:
    IList<UserOwnerShip> userOwnerShip = session.QueryOver<UserOwnerShip>()
                                                    .Where(u => u.UserRole == UserRole.Owner)
                                                    .Where(u => u.IsActive)
                                                    .List<UserOwnerShip>();

我收到了异常:
Type mismatch in NHibernate.Criterion.SimpleExpression: UserRole expected type System.Int32, actual type XXX.XXX.UserRole (which is enum type class)
1个回答

8

如果您想存储枚举的 int 值,映射关系很简单:

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

不需要使用EnumConvention。

4
有时候事情比你想象的要容易,但这些时候并不能弥补那些更加困难的时刻,所以一定要好好享受眼前这一刻。 - Jamie Ide

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接