c# - 在保持排序的同时将有序列表保存到数据库的最佳方法

标签 c# database nhibernate sql-order-by

我想知道是否有人对我在过去几年中遇到过无数次的问题有好的解决方案。

我有一个购物车,我的客户明确要求它的订单很重要。所以我需要将订单持久化到数据库。

最明显的方法是简单地插入一些 OrderField,我会将数字 0 分配给 N,然后按这种方式对其进行排序。

但这样做会使重新排序变得更加困难,而且我觉得这个解决方案有点脆弱,总有一天会回到我身边。

(我将 C# 3,5 与 NHibernate 和 SQL Server 2005 结合使用)

谢谢

最佳答案

好的,这是我的解决方案,可以让与此线程相关的任何人更轻松地进行编程。诀窍是能够在一次更新中更新高于或低于插入/删除的所有订单索引。

在 SQL 查询的支持下,在表中使用数字(整数)列

CREATE TABLE myitems (Myitem TEXT, id INTEGER PRIMARY KEY, orderindex NUMERIC);

要删除 orderindex 6 处的项目:

DELETE FROM myitems WHERE orderindex=6;    
UPDATE myitems SET orderindex = (orderindex - 1) WHERE orderindex > 6;

交换两个项目(4 和 7):

UPDATE myitems SET orderindex = 0 WHERE orderindex = 4;
UPDATE myitems SET orderindex = 4 WHERE orderindex = 7;
UPDATE myitems SET orderindex = 7 WHERE orderindex = 0;

即0 未被使用,因此使用它作为虚拟项以避免出现歧义项。

在 3 处插入:

 UPDATE myitems SET orderindex = (orderindex + 1) WHERE orderindex > 2;
 INSERT INTO myitems (Myitem,orderindex) values ("MytxtitemHere",3)

关于c# - 在保持排序的同时将有序列表保存到数据库的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/330482/

相关文章:

php - 只喜欢一次帖子/评论,laravel

python - 为在 Gunicorn 上运行的 Flask-SQLAlchemy 应用程序选择 DB pool_size

c# - 如何绑定(bind)到 API 类实例的 get-only 属性?

c# - 检索 x :Name or x:Key from Brush

c# - 动态扩展应用程序的功能?

MySQL auto_increment 列声明为 float

c# - 无法加载文件或程序集 crdb_adoplus.dll

c# - 如何在 C# 中将默认的 FlushMode 更改为 Commit?

c# - 无法在 FluentNHibernate 下使用自动 ID 更新 PostgreSQL 表

c# - Process.start 处的 System.NullReferenceException