I'm using client side drag and drop sort ordering for a table of data. The sort order is persisted in the database as a simple integer value. The schema looks like the following:
Id | Title | SortOrder
1 | A | 0
2 | B | 1
3 | C | 2
Data can just be pulled out with a simple ORDER BY
and all is well.
The client side drag and drop I've implemented posts an array of the IDs in the new order, which is then persisted to the database using Dapper as follows (removing service layers for brevity):
[HttpPost]
public ActionResult UpdateSort(int[] ids)
{
if (ids != null && ids.Length > 0)
{
using (var con = Connection.OpenSql())
{
for (var i = 0; i < ids.Length; ++i)
con.Execute("UPDATE Table SET SortOrder = @sort WHERE Id = @id", new { sort = i, id = ids[i] });
}
}
return new HttpStatusCodeResult(200);
}
This works fine, but I wondered if there was a better way to handle the update assuming the client side of things can't change. We have one SQL statement being executed per row at the moment, is there any way to keep it parametrized and batch them? Is it possible to remove the loop entirely?
The number of records being used with this code is small, so it's not a huge problem as it is - the question is really just one of curiosity as I couldn't think of a way to easily order some SQL by an arbitrary array of identity values
I hope this question doesn't break site rules - I did have a check and I think it's ok. I also realize the answer may well just be a 'No', but that being the case I'd still be interested in the confirmation.