c# - Fluent NHibernate (ASP.NET MVC) 中的枚举类型不匹配

标签 c# asp.net-mvc-3 nhibernate fluent-nhibernate

表格模型:

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

和 UserRole 枚举

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)

最佳答案

如果要存储枚举的 int 值,映射很简单:

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

不需要 EnumConvention。

关于c# - Fluent NHibernate (ASP.NET MVC) 中的枚举类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329523/

相关文章:

c# - 共享 Windows 主机上的 Windows 服务

javascript - 如何创建可与嵌入代码一起使用的按钮?

c# - 需要具有 Bind 属性的 MVC 操作方法的指南

c# - 需要关于如何最好地处理列表中不同类型的存储/拆箱的建议,以及在我的情况下什么是最佳的

nhibernate - 使用 NHibernate LINQ 提供程序连接查询的唯一结果

nhibernate - 如何在 NHibernate 中使用不可为空的索引创建列表集合?

c# - OWIN AuthenticationOptions 在运行时在 mvc5 应用程序中更新

c# - 从 Class 转换为 Class B 的设计指南

C# 将控制台应用程序挂接到记事本

nhibernate - 如何使用 Fluent-nhibernate 将集合计数映射到实体