NHibernate HQL的区别和顺序

时间:2011-05-17 09:39:45

标签: nhibernate hql

我最近在旧代码库中从NHibernate 1.2升级到3.1。我已经解决了大多数问题,但我坚持这个问题。 (如果没有对代码库进行大量更改,我无法从HQL更改为另一种访问方法。)

这不是1.2的问题,但升级后我遇到了以下问题。

我有以下HQL:

select distinct c.OwnerUser from Film c order by c.OwnerUser.UserName

导致错误:

[SQL: select distinct user1_.Id as Id33_, user1_.ApplicationId as Applicat2_33_, user1_.UserName as UserName33_, user1_.LoweredUserName as LoweredU4_33_, user1_.MobileAlias as MobileAl5_33_, user1_.IsAnonymous as IsAnonym6_33_, user1_.LastActivityDate as LastActi7_33_, user1_.CreateDate as CreateDate33_, user1_.CountryCode as CountryC9_33_, user1_.PreferredEditionId as Preferr10_33_ from dbo.tbl_Content film0_ inner join dbo.vw_aspnet_Users_With_Id user1_ on film0_.OwnerUserId=user1_.Id, dbo.vw_aspnet_Users_With_Id user2_ where film0_.discriminator in ('film', 'webcamfilm', 'slideshow') and film0_.OwnerUserId=user2_.Id order by user2_.UserName] ---> System.Data.SqlClient.SqlException: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

此代码工作正常,只需要一个我不想要的重复条目。

select c.OwnerUser from Film c order by c.OwnerUser.UserName

如何编写HQL以获得不同的结果?

3 个答案:

答案 0 :(得分:2)

尝试指定联接

select distinct owner from Film c join c.OwnerUser owner order by owner.UserName

答案 1 :(得分:0)

此sql中的错误是子句order by user2_.UserName,但在选择列表中找不到user2_.UserName,这恰好是 select distinct 查询的约束。

尝试

  

选择不同的c.OwnerUser,   来自Film c order的c.OwnerUser.UserName   由c.OwnerUser.UserName

然后遍历结果列表并获取OwnerUser作为(OwnerUser)列表[i] [0]或类似的

答案 2 :(得分:0)

假设所有者用户具有唯一ID,您可以使用以下内容:

select c.OwnerUser from Film c where c.OwnerUser.id in ( select distinct c.OwnerUser.id from Film c) order by c.OwnerUser.UserName