使用Linq to SQL上下移动记录 [英] Moving records up and down with Linq to SQL

查看:55
本文介绍了使用Linq to SQL上下移动记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个功能,用于上下移动记录(排序),并使用Linq将排序顺序保存到SQL .我正在使用 SQL Server 2000,但是如果有解决方案,可以使用较新版本的SQL Server进行升级.我很想听听您对如何做的任何想法.

I need to implement a function for moving records up and down (sorting) and saving the sortorder with Linq to SQL. I am using SQL Server 2000 but I might be able to upgrade if there is a solution for it with a newer version of SQL Server. I would love to hear any thoughts you might have on how to do it.

推荐答案

只需在表中添加一个整数列Index并根据用户输入修改此索引-向上移动只是减少所选记录的索引值并增加前一条记录的索引值.

Just add an integer column Index to the table and modify this index based on the user input - moving up is just decrementing the index value of the selected record and incrementing the index value of the preceding record.

public void MoveUp(Guid id)
{
    Item item = Context.Items.Single(i => i.Id == id);

    if (item.Index > 0)
    {
        Item predecessor = Context.Items.Single(i => i.Index == item.Index - 1);

        item.Index -= 1;
        predecessor.Index += 1;

        Context.SaveChanges();
    }
}

执行相反的操作即可完成操作.如果您需要多个表使用此表,只需使用接口创建通用版本即可.

Do the opposite for moving down and you are done. If you need this for multiple tables, just create a generic version using an interface.

这篇关于使用Linq to SQL上下移动记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆