IList<Companies> companies = NHibernateSession.CreateCriteria(typeof(Companies))
.AddOrder(new RandomOrder())
.SetMaxResults(3)
.List<Companies>();
public class RandomOrder : Order
{
public RandomOrder() : base("", true) { }
public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
{
return new NHibernate.SqlCommand.SqlString("newid()");
}
}
如何从DB中制作随机数据。其中3个。代码我粘贴效果不佳。
答案 0 :(得分:2)
这样的事情可能有用......虽然它需要2个db调用:
public IEnumerable<Company> GetRandomCompanies(int maxSelections)
{
try
{
IList<int> companyIds = _session.CreateCriteria<Company>() // get all available company ids
.SetProjection(LambdaProjection.Property<Company>(c => c.Id)).List<int>();
return _session.CreateCriteria<Company>()
.Add(Restrictions.In(LambdaProjection.Property<Company>(c => c.Id), GetRandomCompanyIds(companyIds.ToList(), maxSelections))) // get 3 random Ids
.List<Company>();
}
catch (Exception xpt)
{
ErrorSignal.FromCurrentContext().Raise(xpt);
}
return new List<Company>();
}
private List<int> GetRandomCompanyIds(List<int> companyIds, int maxSelections)
{
List<int> randomIds = new List<int>();
for (int i = 0; i <= maxSelections; i++)
{
// this will get you the same result all day, new next day
// it might not be what you need, so you could just use a new seed.
Random rng = new Random(DateTime.Now.DayOfYear);
randomIds.Add(companyIds[rng.Next(companyIds.Count)]);
}
return randomIds;
}
编辑:此外,我还没有测试过这个,所以谁知道它会做什么!它应该至少在正确的轨道上。也许有一种方法不需要2分钟的呼叫
答案 1 :(得分:0)
在Nhibernate中,您只需使用SQL
选择随机行var query = "SELECT top 3 * from [Companies] ORDER BY NEWID()";
ISQLQuery qry = session.CreateSQLQuery(query).AddEntity(typeof(Companies));
Companies randomCompanies = qry.List<Companies>();