简体   繁体   English

Linq加入后返回随机实体

[英]Linq Returning random entities after join

I'am trying to return random entities from i join query that i wrote. 我试图从我写的i join查询中返回随机实体。 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. GUID不是随机数。 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. 生成的GUID值甚至可能单调递增,这意味着对序列中每个项目的新guid进行排序将导致每个项目保持完全相同的顺序。

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. orderby Guid.NewGuid()类似于orderby 1.它不会导致随机返回。

I'd suggest letting SQL do the randomization act. 我建议让SQL做随机化行为。 Look at this for an example: 看一下这个例子:

Random row from Linq to Sql 从Linq到Sql的随机行

You can create an empty Random method that LINQ will translate into a Random T_SQL call to SQL. 您可以创建一个空的Random方法,LINQ将转换为对SQL的Random T_SQL调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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