Sort by New Guid for random order

浪尽此生 提交于 2019-12-05 14:47:10

I believe the problem is caused by way LinqPad is creating the DBContext (or whatever it does internally) when you query a database directly (as opposed to creating your own EF connection). If I run this:

using (var context = new MyContext()) {

    var query =
    from x in context.MyTable
    select new {
        x.ID,
        g = Guid.NewGuid()
    };

} 

I get the following SQL

SELECT 
[Extent1].[ID] AS [ID], 
NEWID() AS [C1]
FROM [dbo].[MyTable] AS [Extent1]

Which results in a unique guid for each row. You can alter the Linq to orderby Guid.NewGuid() and you'll get the random sorting that you want.

var query =
    from x in context.MyTable
    orderby Guid.NewGuid()
    select new {
        x.ID
    };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!