4

我正在尝试编写一个返回随机排序结果的查询。我发现这篇文章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;                    
            });

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

4

2 回答 2

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();  
} 
于 2012-05-19T14:57:23.853 回答
1

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

于 2012-05-21T12:49:57.260 回答