c# - Why does Entity Framework ignore order by when followed with distinct? -


i'd know why following join returns values in unordered fashion. distinct imply order of iqueryable passed not guaranteed, therefore ef not bother generating order clause in sql.

 var currentutc = datetime.now;  var data = (from in itemsa      join c in customers on a.fk_customerid equals c.id customersubset      cs in customersubset.defaultifempty()      cs.age > 18)                                          orderby a.id ascending      select new      {        a.id,        a.someproperty,        cs.customeruid,        customername = cs.name,                                       updateutc = currentutc      }).distinct().take(1000).tolist(); 

the strange thing removing distinct adds order clause in inner query of generated sql (you can use linqpad see sql generated eg.)

now if replace last line with

.distinct().orderby(x => s.id).take(1000).tolist(); 

i'm getting order clause in sql, whether or not have orderby a.id ascending in inner query. makes sense, why chaining distinct after orderby not yield same order?

the distinct operation in sql doesn't guarantee order. internally performs sort before determining if rows identical.

even order isn't guaranteed though because query engine can partition data parallel processing, recombine partitioned data produce final result.

to guarantee specific order, order by clause or orderby() call should last 1 before skip() or take()


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -