我有一个ArrayList,我需要能够单击一个按钮,然后从该列表中随机挑选一个字符串并将其显示在消息框中。从表中随机获取元素
我正在使用实体框架6.x和我有一个表问题。
我想随机得到从这个表中10个元素,这是我试过的代码:
List<Question> GetQuestionsRandomly()
{
Random rnd = new Random();
return context.Questions.OrderBy(x => rnd.Next()).Take(10).ToList();
}
,但我得到这个错误信息:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll
Additional information: LINQ to Entities does not recognize the method 'Int32 Next()' method, and this method cannot be translated into a store expression.
我该如何解决这个问题?
谢谢,请你解释一下这个Guid.NewGuid()如何在上面的例子中工作? –
@AimadMAJDOU,Guid生成的将是唯一的,所以你每次都会得到一个随机的顺序,再加上'Guid.NewGuid'将会被转换成SQL中的'NEWID()',所以你的SQL或者类似于'Order通过NEWID()',使用分析器并检查生成的SQL以确保。 – Habib