NHibernate: how to sort a collection by a property of a referenced entity

北战南征 提交于 2019-12-23 03:36:09

问题


I would like to to sort CampaignRetailers by Retailer.Name. However Retailer is a referenced entity on CampaignRetailers. I've tried order-by="Retailer.Name". Is this kind of sorting possible?

<class name="Campaign" table="Campaign">
  <id name="Id">
    <generator class="identity"/>
  </id>
  <set name="CampaignRetailers" table="CampaignRetailers"
       cascade="all-delete-orphan" inverse="true" order-by="Retailer.Name">
    <key column="CampaignId" not-null="true" />
    <one-to-many class="CampaignRetailer" />
  </set>
</class>

<class name="CampaignRetailer" table="CampaignRetailers">
  <id name="Id">
    <generator class="identity"/>
  </id> 
  <many-to-one name="Campaign" column="CampaignId" />
  <many-to-one name="Retailer" column="RetailerId" />
</class>

回答1:


This is not possible.

Use client-side adhoc sorting instead. For example:

sortedCampaignRetailers = campaign.CampaignRetailers
                                  .OrderBy(x => x.Retailer.Name);



回答2:


I usually use instead and I order the collection with order-by using a mapping like the following.

 <bag name="CampaignRetailers" inverse="true" cascade="delete" order-by="Name">
  <key column="CampaignId"/>
  <one-to-many class="CampaignRetailer"/>
</bag>

where Name is the Property of CampaignRetailers. This works for me. I hope also for you.




回答3:


The following should work fine for this (NH 3.x+):

 var retailers = Session.QueryOver<CampaignRetailer>()
                .JoinQueryOver(x => x.Retailer)
                .OrderBy(x => x.Name).Asc
                .List<CampaignRetailer>();


来源:https://stackoverflow.com/questions/6179636/nhibernate-how-to-sort-a-collection-by-a-property-of-a-referenced-entity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!