NHibernate标准连接了许多枚举值

时间:2011-12-06 16:03:38

标签: nhibernate nhibernate-criteria

我有一个名为User的类,在此类中包含UserRole枚举值的集合。

public class User {
    ...
    public ICollection<UserRole> UserRoles { get; private set; }
    ...
}

[Flags]
public enum UserRole {
    Beginner = 1,
    Advanced = 2,
    Expert = 4,
    Admin = 8
}

UserUserRole关系是多对多关系,并使用三个表实现(tblUser,tblRole和tblUserRole仅具有userId和roleId)。 HBM如下:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
   <class name="User, SampleDll" table="tblUser">
   ...
   <bag name="UserRoles" table="tblUserRole" cascade="all-delete-orphan" fetch="join">
      <key column="UserId"/>
      <element column="RoleId" type="UserRole, SampleDll" />      
   </bag> 
   ...
   </class> 
</hibernate-mapping> 

现在我想创建一个标准,其中包含与

相同的语义
select u.* from tblUser u 
left join tblUserRole ur on ur.UserId = u.UserId
where ur.RoleId = @USER_ROLE

是否有可能实现这样的标准(使用queryOver或分离的标准)而没有UserRole enum的单独映射文件?

提前感谢提示。

Mrks

1 个答案:

答案 0 :(得分:0)

你已经有一个标志枚举,它基本上已经是一个值集合。为此你甚至不需要表UserRoles和Roles,只需在User中使用一个简单的列就足够了

[Flags]
public enum UserRoles {
    Beginner = 1,
    Advanced = 2,
    Expert = 4,
    Admin = 8
}

public virtual UserRoles Roles { get; private set; }

<property name="Roles" column="UserRoles"/>

当你真的想要这样的东西时:

public class User {
    ...
    public virtual ICollection<UserRole> Roles { get; private set; }
    ...
}

public class UserRole {
    public virtual int Id { get; set; }

    ...
}

然后

<bag name="Roles" table="tblUserRole" cascade="none"> <!-- none because Roles are somewhat static not per user -->
   <key column="UserId"/>
   <many-to-many column="RoleId" class="UserRole, SampleDll" />      
</bag>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="UserRole" table="Roles">
    <id name="Id"/>
    <!--additional properties-->
  </class>
</hibernate-mapping>