我想知道为什么以下连接以无序方式返回值。明确暗示传递的IQueryable
的顺序不能得到保证,因此EF不会在SQL中生成order by子句。
var currentUtc = DateTime.Now;
var data = (from a in ItemsA
join c in Customers on a.Fk_CustomerID equals c.ID into customerSubset
from cs in customerSubset.DefaultIfEmpty()
where cs.Age > 18)
orderby a.ID ascending
select new
{
a.ID,
a.someProperty,
cs.CustomerUID,
CustomerName = cs.Name,
UpdateUTC = currentUtc
}).Distinct().Take(1000).ToList();
奇怪的是,删除distinct会在生成的SQL的内部查询中添加order by子句(您可以使用Linqpad查看为例如生成的SQL。)
现在,如果我用
替换最后一行.Distinct().OrderBy(x => s.ID).Take(1000).ToList();
我在SQL中获得order by子句,无论我在内部查询中是否有orderby a.ID ascending
。这是有道理的,但为什么在orderby之后链接不同也不会产生相同的顺序?
答案 0 :(得分:5)
SQL中的DISTINCT操作不保证顺序。在内部,它在确定行是否相同之前执行排序。
即使这个顺序也不能保证,因为查询引擎可以对数据进行分区以进行并行处理,然后重新组合分区数据以产生最终结果。
要保证特定订单,ORDER BY
条款或OrderBy()
来电应该是Skip()
或Take()
之前的最后一个