Nhibernate查询顺序随机

时间:2012-05-19 14:50:41

标签: nhibernate

我正在尝试编写一个返回随机排序结果的查询。我发现这篇文章Linq Orderby random ThreadSafe for use in ASP.NET给了我一些基本的线索,告诉我如何做到这一点。但是我得到了以下例外:

从范围''引用的'Accomodations.DAL.Model.Generated.Accomodation'类型的变量'x',但未定义

这是我的问题:

                var query = session.QueryOver<Accomodation>()
                                   .OrderBy(x => (~(x.Id & seed)) & (x.Id | seed)).Asc; // this is the problematic line of code                    

                if (searchParams.District != 0)
                    query = query.Where(x => x.District.Id == searchParams.District);

                if (searchParams.Region != 0)
                    query = query.Where(x => x.Region.Id == searchParams.Region);

                if (searchParams.Location != 0)
                    query = query.Where(x => x.Location.Id == searchParams.Location);

                var futureCount = query.Clone().Select(Projections.RowCount()).FutureValue<int>();

                SearchAccomodationResultItem resultItemAlias = null;

                var futurePage = query                        
                    .SelectList(list => list
                        .Select(x => x.Id).WithAlias(() => resultItemAlias.Id)
                        .Select(x => x.AccomodationType.Id).WithAlias(() => resultItemAlias.AccomodationTypeId)
                        .Select(x => x.Region.Id).WithAlias(() => resultItemAlias.RegionId)
                        .Select(x => x.Name).WithAlias(() => resultItemAlias.Title)
                        .Select(x => x.MaxCapacity).WithAlias(() => resultItemAlias.MaxCapacity)
                        .Select(x => x.MinPrice).WithAlias(() => resultItemAlias.MinPrice)
                        .Select(x => x.MinStayLength).WithAlias(() => resultItemAlias.MinStayLength)
                        .Select(x => x.MainImageName).WithAlias(() => resultItemAlias.ImgSrc)                           
                        )                        
                    .TransformUsing(Transformers.AliasToBean<SearchAccomodationResultItem>())                        
                    .Skip(skip)                        
                    .Take(searchParams.PageSize)
                    .Future<SearchAccomodationResultItem>();

                searchResults = futurePage.ToList();
                numberOfResults = futureCount.Value;                    
            });

任何建议将不胜感激。感谢

2 个答案:

答案 0 :(得分:2)

以下是如何执行此操作的一个很好的示例。这是我目前使用的一种技术。

http://puredotnetcoder.blogspot.com/2011/09/nhibernate-queryover-and-newid-or-rand.html

修改

以下内容来自上述文章,我稍作修改后也包含Skip

public IList<CmsTestimonial> GetRandomTestimonials(int count, int skip) {  
  return Session  
    .QueryOver<CmsTestimonial>()  
    .OrderByRandom()
    .Take(count)  
    .Skip(skip)
    .List();  
} 

答案 1 :(得分:1)

要使用上述方法进行分页,您可以为用户存储种子(可能基于每个会话),然后在SQL中使用RAND(种子)函数 - 因为您使用相同的种子,它将生成相同的伪随机数序列,从而允许分页