加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:34:23 所属栏目:百科 来源:网络整理
导读:表型号: 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 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,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读