如何在NHibernate中查询多对多的关系?

时间:2011-09-06 09:30:06

标签: nhibernate many-to-many hibernate-mapping

我是NHibernate的新手,我想用这项伟大的技术开始开发。

以下是我的关系表:

表架构

tableschemas http://dl.dropbox.com/u/33698629/Entities.JPG

tblAirport
  AirportID
  AirportShortName
  AirportFullName
  AirportTel

tblGroup
  GroupID
  GroupName

tblAirportGroup
  AirportID
  GroupID

我已经将hbm.xml架构定义如下:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="TelDir.Core.Domain.Airport, TelDir.Core" table="tblAirport" lazy="false">
    <id name="ID" column="AirportID" unsaved-value="0">
      <generator class="identity" />
    </id>

    <property name="AirportShortName" column="AirportShortName" />
    <property name="AirportFullName" column="AirportFullName" />

    <set name="Groups" cascade="none" table="tblAirportGroup" lazy="false" access="readonly">
      <key column="AirportId"/>
      <many-to-many class="TelDir.Core.Domain.Group, TelDir.Core" column="GroupId"/>
    </set>


  </class>
</hibernate-mapping>


<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="TelDir.Core.Domain.Group, TelDir.Core" table="tblGroup" lazy="false">
    <id name="ID" column="GroupID" unsaved-value="0">
      <generator class="identity" />
    </id>

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

    <bag name="Airports" cascade="none" table="tblAirportGroup" lazy="false" >
      <key column="GroupID"/>
      <many-to-many class="TelDir.Core.Domain.Airport, TelDir.Core" column="AirportId"/>
    </bag>
  </class>
</hibernate-mapping>

我的映射是否正确?如何检索属于机场的组(GroupName)列表?

我尝试过使用这种语法

ISession session = NHibernateSessionManager.Instance.GetSession();
ISet<Group> rValue = session.CreateCriteria(typeof(Airport))
.CreateCriteria("Groups")
.Add(Expression.Eq("ID", ap.ID))
.List() as ISet<Group>;

但它没有给我任何结果。

你能指导我吗?

致以最诚挚的问候,

1 个答案:

答案 0 :(得分:0)

这是您可以获取包含机场且ID为33的群组的方式,例如:

var groups = session.CreateCriteria<Group>()
                 .CreateCriteria("Airports")
                 .Add(Restrictions.Eq("ID", 33))
                 .List<Group>();