C#String枚举为NHibernate鉴别器

时间:2012-01-14 14:57:09

标签: c# nhibernate enums

我有这种情况无法真正发挥作用。基本上,我有抽象类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“无法确定类型:UserTypeWrapper”。

有谁知道如何实现这一目标?

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:5)

鉴别器值在类中没有看到,因此您不需要任何usertype来从db转换为property。在hbm你也不能使用枚举,你必须直接在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);
    }
}