一、问题描述

  在EF中使用随机排序出现的问题:LINQ to Entities does not recognize the method 'System.Guid NewId()' method, and this method cannot be translated into a store expression .

  解释就是:在使用 LINQ TO Entities 中生成的 sql 语句中找不到该 System.Guid NewId() 方法。毕竟在 sql 中确实不存在该函数。

二、解决思路 

  那就是从数据库中取出数据,拿到数据在进行排序,返回到客户端。

第一种使用 Random 随机排序:

 

var query = BuildQuery(_infoRepository
                .GetAll()
                .PageBy(input)
                .ToListAsync() 
Random random = new Random();
var ent = (from q in query  select new { q, r = random.Next(1, 10) });
var t = ent.OrderBy(x => x.r).Select(x => x.q).ToList();

 

第二种使用 Guid 随机排序:

var query = BuildQuery(_infoRepository
                .GetAll();
var querySetTop = query.ToList().OrderBy(x => Guid.NewGuid());

先使用 ToList() 方法表示已经把数据从数据库加载到客户端了,在进行排序就ok了。

 

相关文章:

  • 2021-10-09
  • 2022-12-23
  • 2021-08-21
  • 2021-12-09
  • 2021-07-13
  • 2022-01-12
  • 2022-02-25
  • 2022-01-04
猜你喜欢
  • 2022-12-23
  • 2021-09-02
  • 2021-11-11
  • 2021-11-19
  • 2022-01-21
  • 2021-10-20
  • 2021-10-29
相关资源
相似解决方案