C#字符串枚举作为NHibernate鉴别器

本文关键字:NHibernate 鉴别 字符串 枚举 | 更新日期: 2023-09-27 18:20:29

我有一个案例不能真正开始工作。基本上,我有抽象类User和扩展类AdminTeacherLabEmployee。以下是我的映射:

<class name="User" table="users" dynamic-update="true" dynamic-insert="true" select-before-update="false">
<id name="Id">
  <column name="id" sql-type="bigint"/>
  <generator class="identity"/>
</id>
<discriminator column="user_type" type="String"/>
...
some irrelevant properties (username, password, email etc.)
...
<subclass name="Admin" discriminator-value="ADMIN"/>
<subclass name="LabEmloyee" discriminator-value="LABEMPLOYEE"/>
<subclass name="Teacher" discriminator-value="TEACHER"/>
</class>

现在,我真的很想使用这个Enum

 public enum UserType
 {
     ADMIN, LABEMPLOYEE, TEACHER
 }

我知道Nhibernate默认情况下会将枚举映射为整数,因此ADMIN将为"0",LABEMPLOYEE将为"1",TEACHER将为"2"。我试着关注这个帖子:

http://codebetter.com/jefferypalermo/2006/03/14/using-enum-strings-with-nhibernate-persistence-level-400/

并定义了UserTypeWrapper:

public class UserTypeWrapper: NHibernate.Type.EnumStringType
{
    public UserTypeWrapper()
        : base(typeof(User.UserType))
    {
    }
}

但它假设enum不是鉴别器,也就是说,我不能将鉴别器类型设置为UserTypeWrapper,因为NHibernate抛出MappingException"Cannot determine type for:UserTypeWrapper"。

有人知道如何做到这一点吗?

如有任何帮助,我们将不胜感激!谢谢

C#字符串枚举作为NHibernate鉴别器

鉴别器值在类中找不到,因此您不需要任何用户类型来从db转换为property。在hbm中,您也不能使用enum,您必须直接在discriminator-value=""中写入值。你想要的可能是:

abstract class User
{
    public virtual UserType Type { get; protected set;}
}
class Teacher : User
{
    public Teacher()
    {
        Type = UserType.Teacher;
    }
}
class LabEmployee : User
{
    public LabEmployee()
    {
        Type = UserType.LabEmployee;
    }
}
switch(someuser.Type)

或使用常规

abstract class User
{
    public virtual UserType Type { get; protected set;}
    public User()
    {
        Type = Enum.Parse(typeof(UserType), this.GetType().Name);
    }
}

并使用映射中值的约定(Fluent NHibernate约定指定鉴别器值)

public class DiscriminatorValueConvention : ISubclassConvention
{
    public void Apply(ISubclassInstance instance)
    {
        instance.DiscriminatorValue(instance.EntityType.Name);
    }
}