4
public IQueryable<CarVersion> GetCar(int carIdToSearch)
{
    return _Dbcontext.CarVersion.Include("CarFactory").
            .Where(x => x.carId== carIdToSearch);
}

I have CarVersion table, which has two columns version and carId. Version column is primary key. There can be multiple version for single carId. CarFactory table has foreign key version from carVersion table. So I'm trying to understand, when I execute above query will it always give me results which are ordered in ascending order. Or will it be based on primary key? Or it can be guaranteed? I looked at MS documentation but it does not say anything about ordering.

jrbedard
  • 3,662
  • 5
  • 30
  • 34
S52
  • 419
  • 1
  • 6
  • 20
  • There is no guarantee that order will be preserved. It may or may not be depending on provider. You can use LINQ `.OrderBy()` method if you need that order. – Fabjan Sep 22 '16 at 14:57

1 Answers1

5

The result you will get depends on the LINQ-provider. If it's Linq-To-Objects the order is stable(read below). It means it will be the same as it was in the source sequence. If it's a database driven LINQ provider like Linq-To-Entities the order is not predetermined.

You need an ORDER BY in sql to ensure a certain order. So you need an OrderBy in LINQ:

return _Dbcontext.CarVersion.Include("CarFactory").
    .Where(x => x.carId== carIdToSearch)
    .OrderBy(x => x.Version);
  • However, even in Linq-To-Objects it's not guaranteed that the order will always be the same. It also depends on the type of the sequence. Set based collections like a Dictionary or HashSet also don't guarantee that the order stays the same as you can read here and here.
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939