You should remember that entityList
is a query - it's not a simple list of entities in memory, and it gets executed over database each time you are 'sorting' it or search some entity. At the same time Linq to Sql tracks objects which was returned from database. And if entity with same Id exists in memory, it is re-used for new queries results.
So, here is what happens:
private void WindowForm_Load(object sender, EventArgs e)
{
entitylist = dbcontext.Entities; // SELECT * FROM Entities
RefreshList();
}
private void ChangeOrder(int argIDPK, int argNewPosition)
{
// SELECT TOP(1) * FROM Entities WHERE IDPK = @argIDPK
// query is executed here
DisplayEntity tempe = entitylist.First(e => e.IDPK == argIDPK);
tempe.OrderInt = argNewPosition;
RefreshList();
}
private void RefreshList()
{
// SELECT * FROM Entities ORDER BY OrderInt
entitylist = entitylist.OrderBy(e => e.OrderInt);
dbcontext.Refresh(RefreshMode.KeepChanges, entitylist);
// query is executed here
listBoxEntities.DataSource = entitylist;
}
Tricky moment here that entities are returned from database ordered by OrderInt field value from database (i.e. original sorting). But when these query results are mapped to memory objects then instances with changed values are used. So, you have entities with locally changed values which are sorted in database values order.
How you can fix that - simply update database value when you are changing it locally:
private void ChangeOrder(int argIDPK, int argNewPosition)
{
DisplayEntity tempe = entitylist.First(e => e.IDPK == argIDPK);
tempe.OrderInt = argNewPosition;
dbcontext.SubmitChanges(); // here we update database
RefreshList();
}
Or use in-memory list instead of IQueryable
here:
List<DisplayEntity> entitylist = null;
private void WindowForm_Load(object sender, EventArgs e)
{
// query is executed only here
entitylist = dbcontext.Entities.OrderBy(e => e.OrderInt).ToList();
RefreshList();
}
private void RefreshList()
{
listBoxEntities.DataSource = entitylist.OrderBy(e => e.OrderInt).ToList();
}
private void ChangeOrder(int argIDPK, int argNewPosition)
{
DisplayEntity tempe = entitylist.First(e => e.IDPK == argIDPK);
tempe.OrderInt = argNewPosition;
RefreshList();
}