我有个案子不能用了。基本上,我有抽象类User
和扩展类Admin
、Teacher
和LabEmployee
。下面是我的映射:
<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>
现在,我真的很想使用这个枚举
public enum UserType
{
ADMIN, LABEMPLOYEE, TEACHER
}
我知道Nhibernate默认将枚举映射到整数,因此ADMIN将是"0",LABEMPLOYEE将是"1“,TEACHER将是"2”。我试着关注这篇文章:
..。和定义的UserTypeWrapper:
public class UserTypeWrapper: NHibernate.Type.EnumStringType
{
public UserTypeWrapper()
: base(typeof(User.UserType))
{
}
}
..。但它假设枚举不是鉴别器,也就是说,我不能将鉴别器类型设置为UserTypeWrapper
,因为NHibernate抛出MappingException“无法为:UserTypeWrapper确定类型”。
有谁知道如何做到这一点吗?
任何帮助都将不胜感激!谢谢!
发布于 2012-01-14 23:49:03
在类中看不到鉴别器的值,因此您不需要任何用户类型来将db转换为属性。在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);
}
}
https://stackoverflow.com/questions/8862999
复制