简体   繁体   中英

Linq Returning random entities after join

I'am trying to return random entities from i join query that i wrote. But it does not return randomly. Entities always come as same before. What can be the problem ? Here is the query

            var query = (from b in db.BrandTbls.AsQueryable()
                     join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
                     join s in db.ShoeTbls on m.ModelID equals s.ModelID
                     join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
                     group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g
                     orderby Guid.NewGuid()
                     select new {g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price,g.Key.PrimaryColor,g.Key.SecondaryColor}).OrderBy(x => Guid.NewGuid()).Take(8);

GUIDs are not random numbers. They are unique numbers . There are a number of ways of generating unique values, many of which are not random at all. It is even possible for generated GUID values to be monotone increasing, which would mean that sorting on new guids for each item in the sequence would result in every item staying in exactly the same ordering.

Shuffling a set of data is a well defined problem, with well defined solutions. You should use one of the well documented solutions to the problem of shuffling to reliably and efficiently shuffle a collection of data.

orderby Guid.NewGuid() would be similar to orderby 1. It won't cause random returns.

I'd suggest letting SQL do the randomization act. Look at this for an example:

Random row from Linq to Sql

You can create an empty Random method that LINQ will translate into a Random T_SQL call to SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM