开发者

LINQ Update database sort order against a dynamic list

开发者 https://www.devze.com 2023-02-15 03:39 出处:网络
I have a database table with a sortOrder column.I display this list to the user and they use jquery to resort the list, then save it back to the server.

I have a database table with a sortOrder column. I display this list to the user and they use jquery to resort the list, then save it back to the server.

After the reorder the list I get a new list in the correct order of all the IDs in that database table.

I need a good way to update this new sort order to the database. What I want is to query the database with a custom sort order based off this list of IDs I g开发者_如何学编程et back from the user. I can then step through that list and increment the sort order from 0.

Bonus points for code in VB, although C# is fine too.

Thanks!


You can't store the sort order in the database unless you have a sort order field in the datatable (or an association with a sort order table that stores the original table's field as an FK). If you have this field then in your linq query do, OrderBy(x=>x.SortOrder)

So you have database record projection

   public class ObjectFromDb{
        int Id{get;set;}
        int SortOrder{get;set;}
   } 

When you get the IQueryable<ObjectFromDb> queryable and the int[] newSortOrder , do this:

     var oldSortedList = queryable.OrderBy(x=>x.SortOrder).ToList()
     foreach(var i=0;i<oldSortedList.Count;i++;){
        oldSortedList[i].SortOrder = newSortOrder[i];
     }
     dataContext.SubmitChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消