C#NHibernate多对多HQL和Criteria查询 - 如何编写?

时间:2014-07-31 09:30:52

标签: c# nhibernate

我在HQL中遇到查询问题。我在角色和用户实体之间有多对多的关联。我必须得到所有活跃的管理员。在用户实体中,我有一个布尔字段“IsActive”,在Role实体中我有用户角色。

我的实体:

    namespace HibernateApp.Entities
    {
        public class User
        {
            public virtual int Id{ get; set; }
            public virtual string Login { get; set; }
            public virtual string Password { get; set; }
            public virtual IList UserRoles { get; set; }
            public virtual Employee Employee { get; set; }
            public virtual bool IsActive
            {
                get;
                set;
            }
}

namespace HibernateApp.Entities
{
    public class Role
    {
        public virtual int Id { get; set; }
        public virtual string RoleName { get; set; }
        public virtual IList RoleUsers { get; set; }
        public virtual IList RolePrivillages { get; set; }
}

映射文件: User.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">

  <class name="HibernateApp.Entities.User, HibernateApp" table="[Users]" lazy="false">

      <id name="Id" column="USER_ID">
        <generator class="native"/>
      </id>

    <one-to-one name="Employee" class="HibernateApp.Entities.Employee, HibernateApp"/>

    <bag name="UserRoles" cascade="all" inverse="true">
      <key column="Id"/>
      <many-to-many class="HibernateApp.Entities.Role, HibernateApp" column="USER_Id"/>
    </bag>

    <property name="Login" column ="Login"/>
    <property name="Password" column="Password"/>
    <property name="IsActive" column="IsActive"/>

  </class>

</hibernate-mapping>

Role.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">

  <class name="HibernateApp.Entities.Role, HibernateApp" table="[Roles]" lazy="false">

    <id name="Id" column="ROLE_ID">

      <generator class="native"/>

    </id>

    <property name="RoleName" column ="RoleName"/>

    <bag name="RoleUsers" cascade="all">
      <key column="Id"/>
      <many-to-many class="HibernateApp.Entities.User, HibernateApp" column="ROLE_Id"/>
    </bag>

    <bag name="RolePrivillages" cascade="all" lazy="false">
      <key column="Id"/>
      <one-to-many class="HibernateApp.Entities.Privillages, HibernateApp"/>
    </bag>

  </class>

</hibernate-mapping>

我的SQL查询以获取活动管理员:

select * from dbo.Roles, dbo.Users WHERE dbo.Roles.RoleName = 'Admin' AND dbo.Users.IsActive = '1'

任何人都可以帮助我使用HQL和条件查询创建异步查询吗?解释会有所帮助。

0 个答案:

没有答案