使用Entity Framework和MySQL的随机顺序 [英] Random order with Entity Framework and MySQL
问题描述
摘要::我想找到一种使用Entity Framework和MySQL进行随机排序的方法(这很重要).该解决方案不应该使用原始sql查询或在从数据库中加载所有值之后进行排序.
Summary: I want to find a way to make random order with Entity Framework and MySQL (that's important). That solution shouldn't use raw sql queries or ordering AFTER loading all values from database.
我尝试过的事情:
我想到了使用NewGuid()从该答案进行随机排序的想法.
I took idea about using NewGuid() for random order from that answer.
代码:
var query = from e in context.Table
orderby Guid.NewGuid()
select e;
var test = query.FirstOrDefault();
总是抛出异常:
An error occurred while executing the command definition. See the inner exception for details.
Inner exception:
FUNCTION MyDatabase.NewGuid does not exist System.Exception {MySql.Data.MySqlClient.MySqlException}
似乎问题在于MySQL没有功能NewGuid().
Seems that problem is that MySQL doesn't have function NewGuid().
如何通过MySQL函数 RAND()
而不是 NewGuid()
进行订购.换句话说,如何在Entity Framework中使用自定义函数 RAND
?
How can I order by MySQL function RAND()
instead of NewGuid()
. In other words, how to use custom function RAND
in Entity Framework?
推荐答案
似乎问题在于MySQL没有功能NewGuid().
Seems that problem is that MySQL doesn't have function NewGuid().
叫我懒,但是问题似乎是MySql没有名为NewGuid的函数.因此,最简单的解决方案不是在MySql中创建一个名为NewGuid的函数吗?
Call me lazy, but the problem seems to be that MySql does not have a function called NewGuid. So wouldn't the easiest solution be to create a function in MySql called NewGuid?
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `NewGuid`() RETURNS char(36)
BEGIN
RETURN UUID();
END$$
DELIMITER ;
创建MySQL NewGuid函数后,问题已为我解决.
Problem is solved for me after creating a MySQL NewGuid function.
问题指出解决方案不应使用原始sql查询",并且这不需要原始的SELECT/INSERT语句.确实需要创建数据库功能.
The Questions states "solution shouldn't use raw sql queries" and this does not require a raw SELECT/INSERT statement. It does require the database function to be created though.
特别注意:我要说的是,从技术上讲,这是MySQL实现中的错误.规范函数被称为由所有数据提供程序支持".NewGuid列在其他规范函数下
Extra note: I would say that this is technically a bug in the MySQL implementation. Canonical Functions are said to be "supported by all data providers" by Microsoft. NewGuid is listed under Other Canonical Functions
这篇关于使用Entity Framework和MySQL的随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!