Question

I am attempting to retrieved randomized records from an Azure SQL database using Entity Framework. I know that if you specify:

OrderBy(x => Guid.NewGuid()) 

that it will randomize the results of the query.

However, If I specify a Guid:

OrderBy(x => guidVariable)

It doesn't randomize the results.

The reason that I want to do this is to be able to page the randomized results with out the randomization being changed with every call:

(I am using a repository pattern that returns an IQueryable)

   recordRepository.FetchByIds(Ids)                                                                                   
                   .OrderBy(x => randomizeKey)
                   .Skip(seedIndex)
                   .Take(pageSize)
                   .ToList();

Repository Code:

 return Context.Entities.Include("Path")
                        .Include("Path")
                        .Where(x => ids.Contains(x.Id));

Am I correct in assuming that Entity Framework interprets the Guid.NewGuid() and has SQL server generate its own? Is there a way around this or am I doing something wrong?

Était-ce utile?

La solution

OrderBy(x => randomizeKey) will be same for each item, so you will get the same sequence at the end

e.g.

new[] {"3", "1", "6"}.OrderBy(x=>5); // results "3", "1", "6"

If you need to get same sequence try using Random Number Generator with same seed

Random r1 = new Random(4);

var result1 = new[] {"3", "1", "6"}.OrderBy(x=>r1.Next());

Random r2 = new Random(4);

var result2 = new[] {"3", "1", "6"}.OrderBy(x=>r2.Next());

you will get same sequence for result1 and result2

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top