Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Guid.NewGuid() doing in LINQ to Entities?

I have a LINQ to Entities written, which is making use of the following OrderBy:

.OrderBy(i => Guid.NewGuid())

The above randomises the ordering of the dataset, so each run of this code produces a different ordering, everytime.

However, if I do any of the following, the dataset is NOT randomised and is the exact SAME for all 3 OrderBy, see below:

.OrderBy(i => new Guid("5fd3e5e7-b172-42f5-a4dd-da4212201a31"))
.OrderBy(i => new Guid("beb7345c-1421-48e0-b177-51b2bb065214"))

Guid g = Guid.NewGuid();
.OrderBy(i => g)

You can see the 3 OrderBy above are using different Guids, so why do they produce the same order? Why is it that Guid.NewGuid() randomises the list everytime I run this piece of code, but the other 3 OrderBy statements produce the same result everytime?

My issue is, I need to pass in a value into a function, which is used within the LINQ to Entities dataset to randomise the results depending on the value, however I also need to be able to pass the same value and retrieve the same order of randomness.

Thanks.

like image 334
Matt Avatar asked Dec 02 '22 13:12

Matt


1 Answers

This behavior when you have Guid.NewGuid() is by design in Entity Framework, it mimics SQL's ORDER BY NEWID(), to allow random ordering. When you specify a constant Guid, it merely orders by this constant value.

like image 187
Ricardo Peres Avatar answered Dec 24 '22 18:12

Ricardo Peres