Ich*_*aki 0 c# entity-framework
我有一个ArrayList,我需要能够单击一个按钮然后从该列表中随机挑出一个字符串并将其显示在消息框中.
我正在使用Entity Framework 6.x,我有一个表格问题.
我想从这个表中随机获取10个元素,这是我尝试的代码:
List<Question> GetQuestionsRandomly()
{
Random rnd = new Random();
return context.Questions.OrderBy(x => rnd.Next()).Take(10).ToList();
}
Run Code Online (Sandbox Code Playgroud)
但我收到此错误消息:
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.
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?
而不是Random.Next使用Guid随机的顺序记录.喜欢:
return context.Questions.OrderBy(x => Guid.NewGuid()).Take(10).ToList();
Run Code Online (Sandbox Code Playgroud)
您收到错误是因为LINQ表达式将被转换为基础数据源语言(在您的情况下可能是SQL),并且由于Random.Next未实现转换为SQL,因此您将获得异常.