Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DbSet.AddRange not preserving order of list in sql database #7894

ksmithRenweb opened this issue Mar 15, 2017 · 1 comment

DbSet.AddRange not preserving order of list in sql database #7894

ksmithRenweb opened this issue Mar 15, 2017 · 1 comment


Copy link

@ksmithRenweb ksmithRenweb commented Mar 15, 2017

What we are seeing is that the order is not preserved when we add a range of values.

Steps to reproduce

  1. Insert an list with a specific order. using an dbset addrange call.
  2. Check database table to review order.

pseudo code:

static void TestAddRange()
  List<TestTable> list = new List<TestTable>(5);
  for(int i=4; i >= 0; i--)
     list.Add(new TestTable{Name = "test", OrderBy = i+1};

  List<TestTable> orderedlist = list.OrderBy(t => t.OrderBy);


  // alternate that fails as well
  //foreach(var temp in orderedlist)
  //  context.TestTable.Add(temp);

  // alternate code that succeeds but results in 5 round trips to database.
  //foreach(var temp in orderedlist)
  //  context.TestTable.Add(temp);
  //  context.SaveChanges()

Result in database
Id , OrderBy
1, 3
2 , 1
3, 4
4, 2
5, 5

Further technical details

EF Core version: 1.1.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Azure Service Fabric (.net 4.5.2)
IDE: (e.g. Visual Studio 2015)


This comment has been minimized.

Copy link

@ajcvickers ajcvickers commented Mar 15, 2017

@ksmithRenweb There is no guarantee that entities will be inserted in the order that they are tracked. There are actually many reasons for this, both around efficiency of internal data structures and the need to re-order where dependencies exist. Also, many stores will not preserve order once inserted, and hence trying to preserve order while inserting doesn't help.

If you are looking for specific key values to be assigned to specific entities, then you might want to look into not using store-generated keys, or perhaps introducing a surrogate key that can be used to preserve the ordering you need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
2 participants
You can’t perform that action at this time.